Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set specific bit in byte

I'm trying to set bits in Java byte variable. It does provide propper methods like .setBit(i). Does anybody know how I can realize this?

I can iterate bit-wise through a given byte:

if( (my_byte & (1 << i)) == 0 ){  } 

However I cannot set this position to 1 or 0, can I?

like image 496
wishi Avatar asked Jan 12 '11 21:01

wishi


People also ask

How do you set a bit in a byte?

Setting a bitUse the bitwise OR operator ( | ) to set a bit. number |= 1UL << n; That will set the n th bit of number . n should be zero, if you want to set the 1 st bit and so on upto n-1 , if you want to set the n th bit.

How do you set a specific bit in Java?

To set any bit we use bitwise OR | operator. As we already know bitwise OR | operator evaluates each bit of the result to 1 if any of the operand's corresponding bit is set (1).

How do I turn off a particular bit in a number?

The idea is to use bitwise <<, & and ~ operators. Using expression “~(1 << (k – 1))“, we get a number which has all bits set, except the k'th bit. If we do bitwise & of this expression with n, we get a number which has all bits same as n except the k'th bit which is 0.


1 Answers

Use the bitwise OR (|) and AND (&) operators. To set a bit, namely turn the bit at pos to 1:

my_byte = my_byte | (1 << pos);   // longer version, or my_byte |= 1 << pos;              // shorthand 

To un-set a bit, or turn it to 0:

my_byte = my_byte & ~(1 << pos);  // longer version, or my_byte &= ~(1 << pos);           // shorthand 

For examples, see Advanced Java/Bitwise Operators

like image 183
driis Avatar answered Sep 19 '22 18:09

driis