• Advertisement

Archived

This topic is now archived and is closed to further replies.

getting bytes from an integer

This topic is 5915 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

hi there, If possible, how do I get the bytes from an integer with only using bit shifts and the binary operators. Thanks!

Share this post


Link to post
Share on other sites
Advertisement
My favorite way of getting bytes from an integer is to let the compiler do it:

  

typedef struct
{
unsigned char b[4];
} b4_t;

...

int i = 15311, j;
b4_t* pb4 = (b4_t*)&i;
for (j=0 ; j<4 ; j++)
{
printf ("byte %d = %d", j, (int)pb4->b[j]);
}



Hope it works, I didn''t actually compile this.

Share this post


Link to post
Share on other sites
another non compiled and sure to fail approach, using only shifts and binary operations (the idea should work, though):

int i;
byte b1,b2,b3,b4;

b1 = (byte)(i&0xFF000000)>>24;
b2 = (byte)(i&0x00FF0000)>>16;
b3 = (byte)(i&0x0000FF00)>>8;
b4 = (byte)(i&0x000000FF);

You know, I never wanted to be a programmer...

Alexandre Moura

Share this post


Link to post
Share on other sites

  • Advertisement