Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c get nth byte of integer

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.

like image 258
Kamran224 Avatar asked Oct 16 '11 21:10

Kamran224


People also ask

How do you extract bytes from an integer?

Problem statement: Given an integer, write a program to extract the nth byte from it. So, if we want to get byte #2, the result would be 0x10. Solution: We can move the required byte to the rightmost position by right-shifting the number by (8 * required byte number).

How many bytes in an int?

The int and unsigned int types have a size of four bytes.

What is 0xff?

Overview. 0xff is a number represented in the hexadecimal numeral system (base 16). It's composed of two F numbers in hex. As we know, F in hex is equivalent to 1111 in the binary numeral system. So, 0xff in binary is 11111111.

What is the hex value stored for for 2 byte integer?

The hex should then be 29(base16) and 49(base16) respectively.


2 Answers

int x = (number >> (8*n)) & 0xff; 

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

like image 89
Vaughn Cato Avatar answered Sep 17 '22 19:09

Vaughn Cato


For the (n+1)th byte in whatever order they appear in memory (which is also least- to most- significant on little-endian machines like x86):

int x = ((unsigned char *)(&number))[n]; 

For the (n+1)th byte from least to most significant on big-endian machines:

int x = ((unsigned char *)(&number))[sizeof(int) - 1 - n]; 

For the (n+1)th byte from least to most significant (any endian):

int x = ((unsigned int)number >> (n << 3)) & 0xff; 

Of course, these all assume that n < sizeof(int), and that number is an int.

like image 32
Dmitri Avatar answered Sep 18 '22 19:09

Dmitri