Reputation: 199
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?
Upvotes: 0
Views: 1255
Reputation: 48258
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
Upvotes: 1