|
-
March 7th, 2011, 10:55 AM
#1
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.
Last edited by CoDEFRo; March 7th, 2011 at 11:02 AM.
-
March 7th, 2011, 11:16 AM
#2
Re: Break down word into 4 bytes using shift and mask
You are asking a question and posting the solution at the same time ?
-
March 7th, 2011, 11:21 AM
#3
Re: Break down word into 4 bytes using shift and mask
 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.
-
March 7th, 2011, 03:03 PM
#4
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
-
March 7th, 2011, 03:36 PM
#5
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 );
Last edited by S_M_A; March 7th, 2011 at 06:12 PM.
-
March 7th, 2011, 05:01 PM
#6
Re: Break down word into 4 bytes using shift and mask
-
March 7th, 2011, 05:02 PM
#7
Re: Break down word into 4 bytes using shift and mask
 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.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|