• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1335
  • Last Modified:

extract a byte out of an integer

Hi,

How do I extract a byte out of an integer. For example, I like to get the first byte of a 4-byte integer.
Thanks
0
mycuti08
Asked:
mycuti08
  • 4
  • 2
1 Solution
 
evilrixSenior Software Engineer (Avast)Commented:
>> For example, I like to get the first byte of a 4-byte integer.
Something like below...
int main()
{
	unsigned int dw = 0xFFEEDDCC;
	unsigned char byte0 = dw & 0xFF;
	unsigned char byte1 = (dw >> 8) & 0xFF;
	unsigned char byte2 = (dw >> 16)  & 0xFF;
	unsigned char byte3 = (dw >> 24) & 0xFF;
}

Open in new window

0
 
evilrixSenior Software Engineer (Avast)Commented:
Re: { http:#21759102 }

For each byte we need to use bitwise and (&) to mask in only 1 byte, we then just bit-shift 0, 8, 16 or 32 bits to the right so we can mask in byte 0, 1, 2 or 3 and exclude the rest. The bit-shift operators don't behave as you'd expect with signed types (they take into account the sign of the type and maintain it during shifting) so when doing bitwise arithmetic it is always best to use unsigned types.
0
 
evilrixSenior Software Engineer (Avast)Commented:
You might find this tutorial helpful: http://www.cprogramming.com/tutorial/bitwise_operators.html
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
mycuti08Author Commented:
Thanks evilrix. It worked great
0
 
evilrixSenior Software Engineer (Avast)Commented:
>> Thanks evilrix. It worked great
Did you understand how/why it worked?
0
 
mycuti08Author Commented:
yes I did.
Thanks evilrix
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now