gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

C/C++ > Using structs and bitfields to map memory

#11353 - jerkize - Fri Oct 03, 2003 2:13 am

I'm still new to GBA development. In all of the sample code that I've
seen, everyone is using symbols and bit shifting to modify sections of
GBA memory. Does anyone see any pros/cons with mapping a struct to
GBA memory? As an example, here's what I'm doing for sprites (please
excuse my variable names if they don't make sense):

Code:

  typedef struct Sprite {
    u16 y                 : 8;
    u16 allow_transforms  : 1;
    u16 double_it         : 1;
    u16 alpha_mode        : 2;
    u16 allow_zoom        : 1;
    u16 color_mode        : 1;
    u16 yshape            : 2;
    u16 x                 : 9;
    u16 scale             : 3;
    u16 hflip             : 1;
    u16 vflip             : 1;
    u16 xshape            : 2;
    u16 id                : 10;
    u16 priority          : 2;
    u16 palette           : 4;
    u16 rotation_register : 16;
  };


These are what I see as the benefits:


  • The code is more self-documenting.

  • It is simpler to modify a field, meaning you don't have to OR
    everything together just to update, say, the x position.

  • I'm hoping it is faster but this is just a gut feeling, nothing more.



Thanks for any feedback.

#11356 - tepples - Fri Oct 03, 2003 3:32 am

Big con: Different compilers have different ideas of how to lay out the bits in a bitfield, so your code may break from one version of the compiler's C ABI to the next.
_________________
-- Where is he?
-- Who?
-- You know, the human.
-- I think he moved to Tilwick.

#11370 - torne - Fri Oct 03, 2003 4:28 pm

It's not faster; it's exactly the same speed at best; and as tepples said, there is no requirement that bitfields in a struct are composed in the same way between different compilers, so if an ABI change happens your code will break. =)

Also, if you use bitfields, then it will be slower if you DO want to change more than one entry at a time: if you change, say, the X and the Y location through bitfield access, it will be two binary operations as the compiler doesn't seem to be able to optimise across them, whereas if you do it with shifts..etc it will only be one (albiet a slightly more complex one, but the code I just compiled and disassembled was much better than the bitfield case).