Mario Orozco Mario Orozco - 1 year ago 71
Java Question

is there a straightforward way to turn off an integer bit in java?

im trying to simplify my database by saving boolean data in numeric fields, right now im doing this to turn on and off a bit.

int turnBit(int input, int bit, boolean value){
input = input | (1<<bit);
input = input | (1<<bit);
input = input ^ (1<<bit);
return input;

is there any way to turn off the bit without turning it on before?

Answer Source

You are using the bitwise 'or' operator to turn on a bit, and this is correct:

0001 | 0010 results in 0011

You can use the bitwise 'and' function to turn off a bit:

1101 & 1110 results in 1100

So to turn off one bit of a value, you make a 'bit mask' which has all the bits you do NOT care about set to 1, and the one that you want to turn off set to 0; that will 'turn off' that bit in the value.

If you have a mask for turning on a particular bit -- that is, one with 0 in each position you don't want to change and a 1 in the position you do want to change, you can transform it into the "turn off" bit mask by applying java's bitwise 'not' operator (~), i.e., ~0010 results in 1101.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download