c get nth byte of integer

Kamran224 picture Kamran224 · Oct 16, 2011 · Viewed 72.1k times · Source

I know you can get the first byte by using

int x = number & ((1<<8)-1);

or

int x = number & 0xFF;

But I don't know how to get the nth byte of an integer. For example, 1234 is 00000000 00000000 00000100 11010010 as 32bit integer How can I get all of those bytes? first one would be 210, second would be 4 and the last two would be 0.

Answer

Vaughn Cato picture Vaughn Cato · Oct 16, 2011
int x = (number >> (8*n)) & 0xff;

where n is 0 for the first byte, 1 for the second byte, etc.