How do I access aligned bit data of different types?

I wasn't even sure if the topic question is right...but here's my question

Say I have object:
1
2
3
4
5
struct Test{
int a;
char b,c,d;

};


Now whenever I declare this object, the 4 bytes of int and 3 byte of char will be sitting side by side in memory as well as some extra padding due to compiler preference to end data types on 4 byte boundaries (so we're really at 8 bytes here)

I want to create a mask of say long long int, 8 bytes of int.. I create my mask and now...I am confused, how do I apply my long long mask to Test type?

I know of the bitwise operators | ~ & etc. That isn't the issue, the issue is, I want to use my long long as a way to mask the whole Test object, meaning at << 32, I am attempting to mask char b (as that would exist on the 5th byte).

I know in memory the int and char bytes are sitting right next to each other, so it should be possible to access all of them with a single mask that is large enough to do so.

Is there a way of doing this without casting my Test obj to another type?
Last edited on
well you can use the bitwise operators that you already mentioned to shift the bits into it..

Or you might be looking at checking out a union. that might handle what you're looking for.
Hmm...
Well, I don't know about unions, but I think the simplest way is to cast Test * into void * and then into char *. Or maybe into long long *, since you can't use the shift operators on an array of bytes. Then again, your structure doesn't fit nicely into the 64 bits, so I'm not sure what will happen if you do that.
Aakanaar
1
2
3
4
long long int Mask = 255;
Mask = Mask << 32; //bitshifting to the left by 4 bytes, my values are resting on the 5th byte

Test = Mask;


Only member variable 'a' will be written to and it'll be a large negative number...I can't use the other bitwise operators without defining that bitwise operator in my object which would defeat the entire purpose of doing a bitwise time saver device by forcing it to call a function to do it...

Helios
I know casting would work, and it would work exactly if casted to the long longs. But again, that it would defeat the purpose of making it a timesaver.

By the way, thanks for the help on the alpha blending thing, I noticed you do a /255 in your equation, you could just do a >>8 which amounts to same thing except you lose a .5 accuracy (which doesn't matter a whole bunch when you're storing channels as uchars)
Nope. 255 equals 1.0, so I need to divide by 255, not 256.
Topic archived. No new replies allowed.