maxematician
maxematician

Reputation: 199

How do you flip a specific bit in a Java primitive byte?

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

Answers (2)

Harsha_rai
Harsha_rai

Reputation: 1

Try this

int i=3; 
b = (byte) (b ^ (1 << i));

Upvotes: 0

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

Related Questions