Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to change how a variable is stored in memory (bit sizes)?

Let's say I have the following datastructure (pseudo code):

struct
{
  uint8  id;
  bool   failure;
  uint8  value;
}  

Now let's say I want the data stored in the following way in memory:

bit 7-6: id bit 5: failure bit 4-0: value

Is there anyway to do that in C/C++/Visual Studio? I know you can do it in Ada, but that doesn't mean much.

Edit: Sorry for not being clear, I do need a particular layout in memory. This structure will be used for messages being sent across a serial channel and it needs to conform to the interface spec

like image 689
mikehabibi Avatar asked Jan 29 '26 04:01

mikehabibi


1 Answers

You can use C bitfields:

struct
{
  uint8 id : 2;
  bool failure : 1;
  uint8 value : 5;
};

However, although this may reduce the amount of memory used for the struct*, this does not guarentee any particular in-memory layout; the specific bits assigned for each field will depend on your compiler and/or platform ABI. If you need to assign specific bit indices to specific fields, you will need to pack and unpack manually. Or, if your code does not need to be portable, you could look up how your compiler packs bitfields, and order the members of your struct accordingly.

* - The C standard puts very few restrictions on the layout of bitfields, and C++ even less. Usually it will result in less memory usage, but if the compiler decides that the smallest bitfield allocation unit it'll use is a 32-bit field or something, then the size might actually increase. See ISO/IEC 9899:1999 (E) §6.7.2.1/10

like image 185
bdonlan Avatar answered Jan 31 '26 19:01

bdonlan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!