Break down word into 4 bytes using shift and mask
If I have a word: unsigned int x and I'd like to break it down into four bytes: unsigned char b1, b2, b3, b4, can someone tell me the proper syntax on how to do this. I know you have to shift and then mask, but am not sure how to go about doing it from a code perspective.
Code:
b1 = x //&& mask all but the lowest order byte
b2 = x >> 8 //&& mask all but the lowest order byte
b3 = x >> 16 //&& mask all but the lowest order byte
b4 = x >> 24//&& mask all but the lowest order byte
??
Thanks.
Re: Break down word into 4 bytes using shift and mask
You are asking a question and posting the solution at the same time ?
Re: Break down word into 4 bytes using shift and mask
Quote:
Originally Posted by
Skizmo
You are asking a question and posting the solution at the same time ?
I'm not sure what the correct syntax is for the mask I need and just wanted to make sure I did the shift correctly.
Re: Break down word into 4 bytes using shift and mask
Your code looks ok if you add masking.
A WORD has only two bytes, you cannot break it into four. You need a DWORD to have four bytes.
BTW, take a look at the following macros:
LOWORD, HIWORD, LOBYTE, HIBYTE
Re: Break down word into 4 bytes using shift and mask
You don't need any masks but unless you use a very low compiler warning level you will get some warnings so you probably want to add a cast.
Code:
unsigned char b1 = static_cast<unsigned char>( x );
unsigned char b2 = static_cast<unsigned char>( x >> 8 );
unsigned char b3 = static_cast<unsigned char>( x >> 16 );
unsigned char b4 = static_cast<unsigned char>( x >> 24 );
Re: Break down word into 4 bytes using shift and mask
Re: Break down word into 4 bytes using shift and mask
Quote:
Originally Posted by
srelu
Your code looks ok if you add masking.
A WORD has only two bytes, you cannot break it into four. You need a DWORD to have four bytes.
BTW, take a look at the following macros:
LOWORD, HIWORD, LOBYTE, HIBYTE
Thanks. Yeah DWORD is what I meant, 32 bits.