Archived

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

Arch_Spider

getting bytes from an integer

Recommended Posts

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