Reputation: 278
I am trying to change some bits in a byte[]
But I have not been able to find the correct condition to change the value
Lets say my byte is 11010101 I need to check if the 1st bit is 1 and change it to 0
Thanks
Upvotes: 0
Views: 3661
Reputation: 5148
you need to first check if the nth bit is 1 or 0 , if it is 1 then change it to 0.
if(number & (1 << (n-1)){
number &= ~(1 << (n-1));
Upvotes: 0
Reputation: 168
In java, byte is a signed type, therefore its value can be between -128 and 127. The data are stored in two's complement, which means the first (the most significant) bit/digit indicate whether the number is negative (1) or non-negative (0). For further information read this: https://en.wikipedia.org/wiki/Two%27s_complement
So you can simply add 128 to it
byte myByte = 111;
myByte = (byte)(myByte + 128);
Second method is using XOR operation to the first digit. This code should do it:
byte myByte = 111;
myByte = myByte ^ 0x80;
Upvotes: 0
Reputation: 43
Bitwise operations are what you are looking for. I'm sure there are more efficient implementations, but I'll just illustrate the point in this answer.
I'm going to waste space by representing bits using bytes in Java:
//11010101 has a value of -43 because bytes are signed by Java
//MSB
byte bit1 = 1;
byte bit2 = 1;
byte bit3 = 0;
byte bit4 = 1;
byte bit5 = 0;
byte bit6 = 1;
byte bit7 = 0;
byte bit8 = 1;
//LSB
Even though I am only setting a value of 0 or 1 to my bytes, java is using 8-bits to store them. That means, in memory, my bit1
value takes up 1 bytes (2 nibbles) of space:
0 0 0 0 0 0 0 1
I can "shift" this value up in this space by using a bitwise shift operator. There are two flavors, up and down. I'll shift my bit up by one:
bit1 << 1;
That shifts the bits of the integer bit1
up by one (adding a zero to the lowest bit in memory) like so,
0 0 0 0 0 0 1 0
The decimal value of bit1
is now 2!
We now have the tool we need to shift a value up to it's position in the byte, we just need to shift each of our bits and bitwise "OR" them together using the "|" operator:
byte myByte = 0;
myByte = (byte)((bit1 << 8) | (bit2 << 7) | (bit3 << 6) | (bit4 << 5) | (bit5 << 4) | (bit6 << 3) | (bit7 << 2) | (bit8 << 1) | bit8);
I make sure to cast the result of the shifts and bitwise ORs to a byte ensuring the correct format of my result. myByte
now looks like this in memory:
1 1 0 1 0 1 0 1
The value of this byte in decimals is -43 because bytes are signed in Java. You can use 2's compliment to check this by hand.
Now, to set the first bit of your byte, you just use a bitwise AND with a mask!
myByte = (byte)(myByte & 0b11111110);
The decimal value of myByte
is now -44.
Upvotes: 1