using bitwise operations how could i split a 16 digit binary number into two seperate 8 digit binary numbers?

Printable View

- 03-24-2007black_watchbitwise operations
using bitwise operations how could i split a 16 digit binary number into two seperate 8 digit binary numbers?

- 03-24-2007KONI
like this:

Code:`int number_16bit = 0xFFFF;`

int number1_8bit = (number_16bit >> 8) & 0xFF;

int number2_8bit = number_16bit & 0xFF;

- 03-24-2007black_watchQuote:

Originally Posted by**KONI**

i obtained the left side of the 16 digit binary number by doing the following

Code:`int value2 = FileSize >> 8;`

- 03-24-2007KONI
Number2 will contain the least significant bits of your input since I masked it with an 0xFF mask. The bitwise AND together with the mask (0xFF) keeps the 8 least significant bits without changing their values and sets the rest to 0.

Code:`int value2 = FileSize >> 8;`

*exactly*16 bits, it won't work if FileSize is 17 bits or above. By masking with an 8 bit mask, you're making sure that the rest of the bits is discarded/set to zero. - 03-24-2007black_watchQuote:

Originally Posted by**KONI**

so if i and the digits 1 0 1 1 1 1 1 1 0 1 0 1 1 1 1 0 with 0xFF the output should be 0 1 0 1 1 1 1 0. - 03-24-2007KONI
exactly, this is because the mask 0xFF has every bit set to 0 if you bitwise AND it with a number larger than 8 bits. And because, if you AND whatever bit with 0, the result is 0, you eliminate all the bits apart from the 8 first ones.

- 03-24-2007black_watch
But for joining them back together as one int would i have too loop around each individual bit, for both of the seperate numbers, comparing them against a 16 bit 0 number?

- 03-24-2007twomers
Or you could just shift them in together in two swppos. Kind of the opposite of what you did to extract them in the first place.

- 03-24-2007KONIQuote:

Originally Posted by**black_watch**

Code:`number_16bit = (number1_8bit << 8) | number2_8bit;`

- 03-24-2007black_watch
That worked great, thanks a lot guys, i think im understanding this whole bitwise thing a little better now.