Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a hex number

Tags:

c

newbie question.

Say for example, I have the hex number 0xABCDEF, how would i split it into 0xAB,0xCD and 0xEF? Is it like this?

unsigned int number = 0xABCDEF
unsigned int ef = a & 0x000011;
unsigned int cd = (a>>8) & 0x000011;
unsigned int ab = (a>>16) & 0x000011;

Thanks

like image 370
Daniel Avatar asked Oct 09 '12 10:10

Daniel


People also ask

What is Hex 0x0A?

0x is the prefix for hexadecimal notation. 0x0A is the hexadecimal number A, which is 10 in decimal notation.


2 Answers

Use 0xff as your mask to remove all but 8 bits of a number:

unsigned int number = 0xABCDEF
unsigned int ef = number & 0xff;
unsigned int cd = (number>>8) & 0xff;
unsigned int ab = (number>>16) & 0xff;
like image 118
simonc Avatar answered Oct 19 '22 21:10

simonc


unsigned int number = 0xABCDEF
unsigned int ef = number & 0xff;
unsigned int cd = (number >> 8) & 0xff;
unsigned int ab = (number >> 16) & 0xff;

Instead of the bitwise and (&) operation, you might intead want ef, cd, ab to be unsigned char types, depending on the rest of your code and how you're working with these variables. In which case you cast to unsigned char:

unsigned int number = 0xABCDEF
unsigned char ef = (unsigned char) number;
unsigned char cd = (unsigned char) (number >> 8);
unsigned char ab = (unsigned char) (number >> 16);
like image 37
Trevor Avatar answered Oct 19 '22 21:10

Trevor