0

I have never used bytes in Java before, so I am unfamiliar with the sytnax for manipulating bytes and bits. I searched how to do this task, but I can't find a simple solution.

I have a byte b. b has eight bits. I would like to flip the ith bit of b to its negation (0 -> 1, 1 -> 0). How do I do this?

maxematician
  • 199
  • 7

2 Answers2

1

I think this will work:

byte b = 0; // initial val ...0000000
final int theNumberofTheBitToFlip = 2; // bit to flip
b = (byte) (b ^ (1 << theNumberofTheBitToFlip));
System.out.println(b); // result ...0000100 = 8
b = (byte) (b ^ (1 << theNumberofTheBitToFlip));
System.out.println(b);// result ...0000000 = 8
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

Try this

int i=3; 
b = (byte) (b ^ (1 << i));
swiftBoy
  • 35,607
  • 26
  • 136
  • 135