Hello,
I am working on this code where I need to store a 32 bit number but in two variables. For example:
1 2 3 4 5
int num = 16777215;
unsignedshort MSB = 255;//the last 16 bits of num
unsignedshort LSB = 65535;//the first 16 bits of num
However I am not sure how to do this. Num will be an input from an user via a text box. I have used logical AND and that doesn't work. Any help will be greatly appreciated.
Try using a bit-wise and. I don't recall the syntax off the top of my head., but it should be something like this:
1 2 3 4
int num = 16777215;
unsignedshort MSB, LSB;
MSB = num & 65535; //0000_0000_0000_0000_1111_1111_1111_1111
LSB = (num & 4294901760) / 65536; //1111_1111_1111_1111_0000_0000_0000_0000
This should mask the 32 bit value, then assign the resulting masked value to the smaller variables. The division on the second effectively shifts the bits right 16 bits. This is necessary because when a larger number is assigned to a smaller variable, if I remember correctly, the right most digits are truncated. This division allows the correct value to be kept.
Toum,
Thanks thats exactly what I was trying to do, I had the first part correct. Ok, now I want to know how put MSB and LSB together to get back num(16777215). I will have to display the values stored in LSB and MSB at some point.
Toum,
Thanks alot!!!However , I am not getting the original num when putting the LSB and MSB back together by hand. Code works but I was doing it by hand just to make sure that I am fully understanding what the code is doing. My take is that the MSB is left shifted 16 places in num and the LSB is OR with the LSB of num, which is 0's. Am I understanding this correctly?