using bitwise operations how could i split a 16 digit binary number into two seperate 8 digit binary numbers?
Printable View
using bitwise operations how could i split a 16 digit binary number into two seperate 8 digit binary numbers?
like this:
number2 will contain the least significant bits (right bits) and number1 will contain the leftmost bits. Since number1/number2 are only 8 bits, you can also use a char type to store the content.Code:int number_16bit = 0xFFFF;
int number1_8bit = (number_16bit >> 8) & 0xFF;
int number2_8bit = number_16bit & 0xFF;
in that case will number2 the one that contains the least significant bits always contain 1111 1111?Quote:
Originally Posted by KONI
i obtained the left side of the 16 digit binary number by doing the following
I am then going to conver the integer values into char values.Code:int value2 = FileSize >> 8;
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.
The code above only works if FileSize is 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.Code:int value2 = FileSize >> 8;
I know it will always be exactly 16 bits as i put the data in as 16 bits, thanks a lot for your help, anding a binary number with that mask only checks the first 8 digits and then set the rest to 0?Quote:
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.
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.
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?
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.
Like this:Quote:
Originally Posted by black_watch
C makes sure that, if you left shift a number, only 0's will be added.Code:number_16bit = (number1_8bit << 8) | number2_8bit;
That worked great, thanks a lot guys, i think im understanding this whole bitwise thing a little better now.