I have to take a binary data in java and perform shifts on it. For e.g. 11110000 when I right shift it by 2 , i.e. 11110000>>00111100
The problem is that, I don't know how to store such a data in Java, as the byte type converts it to decimal format. I need to use the bit at position 6 and XOR it with some other value.
I just need to know how I can achieve the ability to store binary data and perform the required shifts.
If you're using an integer it'll display it in a number format, you can work around it using Integer.toBinaryString(yourByte)
Second, if you're using an integer to store a binary number in the format of 1...
(the leftmost bit is 1) then using the operation >>
will shift the number right but enter a "new" 1
into the leftmost bit. What you want to do in such case is actually use >>>
which prevents that.
If you're using an int
to store your byte, and you want to start doing all kind of bit manipulations than you'll have to use a mask
, for example, switching between the 3rd and the 5th bits:
int number = 7; //just an example, here binary rep: 00111 => requested output will be 10011
System.out.println("number = " + Integer.toBinaryString(number));
int mask3Bit = 4;//binary rep: 0100
System.out.println("mask3Bit = " + Integer.toBinaryString(mask3Bit));
int mask5Bit = 16; //binary rep: 10000
System.out.println("mask5Bit = " + Integer.toBinaryString(mask5Bit));
// now we'll create a mask that has all the bits on except the 3rd and 5th bit:
int oppositeMask = -1;
oppositeMask ^= mask3Bit;
oppositeMask ^= mask5Bit;
System.out.println("oppositeMask = " + Integer.toBinaryString(oppositeMask));
//check if the 3rd bit is on:
mask3Bit = number & mask3Bit;
//shift twice to the right
mask3Bit <<= 2;
System.out.println("mask3Bit = " + Integer.toBinaryString(mask3Bit));
//now do the same with the 5th bit
//check if the 5th bit is on:
mask5Bit = number & mask5Bit;
//shift twice to the right
mask5Bit >>= 2;
System.out.println("mask5Bit = " + Integer.toBinaryString(mask5Bit));
//now we'll turn off the 3rd and 5th bits in the original number
number &= oppositeMask;
System.out.println("number = " + Integer.toBinaryString(number));
//and use the masks to switch the bits
number |= mask3Bit;
number |= mask5Bit;
//let's check it out now:
System.out.println("new number = " + Integer.toBinaryString(number));
OUTPUT:
number = 111
mask3Bit = 100
mask5Bit = 10000
oppositeMask = 11111111111111111111111111101011
mask3Bit = 10000
mask5Bit = 0 //here it's zero cause the original number has zero in the 5th bit and we used &. If the bit was on we would have gotten '100'
number = 11
new number = 10011