# Solved: java bitwise operators question



## csatennis (Mar 3, 2007)

As I understand it, if you define a variable as a byte, then by using the | operator and the >>> operator, you can update an individual bit in the designated byte.

For example, in a program where b is defined as an array of bytes, you can do the following:

b[0] = (byte)(b[0] | 0x80>>>0);

which will move a 1 in the first bit (bit 0) of byte 0.

if i do a System.out.println(b[0]) it does show a value of 128, indicating that the 0 bit was indeed set.

However, I need to not only set various bits in random bytes, I have to go back and interrogate the individual bits later to see if they are set.

I think, in some way, you use the & operator, but not sure how.

My questions are:
1. Did I set the bit properly?
2. How do I determine later if the bit was saved? I can't simply check the value of the byte, because if the first and last bit was set to 1, then the value would be 129. I need to write some kind of loop where I check each bit and interrogate it.

thanx

bob


----------



## JimmySeal (Sep 25, 2007)

I don't have a tremendous amount of experience with bitwise operators, but I'll help as much as I can.

Firstly, the *>>>0* part of your example is unnecessary. Shifting a value by 0 places just leaves it the way it is.

And yes, you can use the & operator to determine the value of a single bit. Here's some code to demonstrate that:


```
byte testByte = 57;
		int bitNumber = 1;
		String binary = "";
		// checkBit is a char, because byte can only store positive values up to 127
		for(char checkBit = 1; checkBit <= 128; checkBit <<= 1)
		{
			boolean isSet = (testByte & checkBit) != 0;
			System.out.println("Bit number " + bitNumber + " is " +
					(isSet ? "" : "not") + " set.");
			binary = (isSet ? '1' : '0') + binary;
			bitNumber++;
		}
		
		// one more illustration:
		System.out.println("testByte ("+ testByte +") in binary:\n" + binary);
```
Output:
Bit number 1 is set.
Bit number 2 is not set.
Bit number 3 is not set.
Bit number 4 is set.
Bit number 5 is set.
Bit number 6 is set.
Bit number 7 is not set.
Bit number 8 is not set.
testByte (57) in binary:
00111001


----------



## csatennis (Mar 3, 2007)

After some research it appears that I can set a bit using the | bitwise operator.

byte x = (byte)(x | 0x80>>>3);

which sets bit number 3

To check to see if it is set:
byte x = (byte)(x & 0x80>>>3);

if x = 0 then the byte was not set, otherwise it was set.

bob


----------

