
bitwise operations
Hi, I am trying to follow a book example on referencing union members and the method below has been used without explanation. Could anyone explain please?
union u {
char ch[2];
int num;
};
int unioninit (union u val); /*declare function to return int*/
main()
{
union u val;
int x;
x = unioninit(val) /*this assigns values two chars to the ch array*/
printf("the two characters held by the union are:\n");
printf("%c\n", x & 0x00FF); /* this is my problem */
printf("%c\n", x>>8);
.............
What I don't understand is how comparing x and 0x00FF has the effect of displaying the first byte of the int num variable.
If you don't include the bitwise operator surely it does the same since the %c only asks for the first byte???
And where did that value 00FF come from anyway?
Can anyone help?
Bukko

x & 0x00FF
This is called a bitstrip.You are bitwise anding the value of x with 0xFF. From learning about bitwise operators you will find that anything anded with zero is zero and a 1 anded with 1 is 1. so to see how this works lets say that x is a short with a value of 369 which is 0000000101110001 in binary.Now lets just strip this to a byte value by anding with 0xFF which is 0000000011111111 in binary...
heres the result..
0000000101110001 &
0000000011111111 =
0000000001110001.
So you see that the bits that were anded with 1 are preserved and the bits that were anded with zero are destroyed. One possible reason that this is useful is in conserving memory.Windows, because it is still based on some code that was used when conserving memory was still important uses this all the time. for instance when you respond to a WM_SIZE message you recieve a 32 byte value back that has the x coord in the low word and the y coord in the high word. You can access these values by anding with 0xFFFF0000 and 0x0000FFFF respectively.

so there are certain hex values such as FF which have an established effect when anded with an unknown variable.
so here using FF has the effect of splitting the memory block in half?

so an int variable will take up two bytes  16 bits  and by anding the value with 0000000011111111 (00FF) you effectively zero the first half of the value.
Is that right?
If so, in my example the function initialises the ch[2] array with two chars and returns that as a single int value.
Doing this bit stripping action (as above) then zeros the bits on the left.
Are the bits on the left in the 'higher' memory location?
If they are then that answers my question.
I couldn't see how zeroing the first half would display the first char variable but if the first half represents the 'higher' or second char variable's position then it would work perfectly.
Am I right now?
Sorry to be so slow.....