Now that the shock is passed, let's see how to set a specific bit in a byte object:
public void set(int bit){
byte b = (byte)(1 << (bit - 1));
res |= b;
}
Assuming res is our byte variable. And yes, the cast is there since the shift operation << returns an int, therefore it must be cast back to byte type, otherwise the bitwise OR would later fail!
And the -1 is of course because we start with position 0 on the right. Note that using the bitwise OR will set the bit ONCE and never revert it back!
No comments:
Post a Comment
With great power comes great responsibility