Grim
Grim

Reputation: 1974

Why bitwise AND gives different byte?

A byte in java is 8 bit long. A & operator does a bitwise andoperation.

A hexadecimal representation takes two hex-chars 0-F.

A 0xFF is one byte.

If I think about the & operation I think the processor does this:

   Bit no: 1 2 3 4 5 6 7 8 
   Binary: 0 0 0 0 0 0 1 0 = decimal 2
Operation: & & & & & & & &
    Value: 1 1 1 1 1 1 1 1 = 0xFF
----------------------------------------
   Result: 0 0 0 0 0 0 1 0 = decimal 2

Because all binaries remain unchanged, it leads me to think that we do not need the & 0xFF.

Code

public static void main(String[] args) {
    byte b = -1;
    System.out.println(String.valueOf(b).concat(" and ").concat(String.valueOf(b & 0xFF)));
}

Result

-1 and 255

If my assumption (we don't need & 0xFF) is correct, why the difference?

Upvotes: 2

Views: 74

Answers (2)

k_ssb
k_ssb

Reputation: 6252

0xFF is an int, not a byte, so b & 0xFF is also an int. To get the result you want, you either need to do byte arithmetic (which Java doesn't allow -- all datatypes smaller than int are implicitly converted to int before performing operations), or your mask 0xFF must have 1's for every bit in the int (all 32 of them). See for example the following:

System.out.println(0xFF);            // 255. (only 8 of 32 bits are 1)
System.out.println((int)0xFF);       // 255. (only 8 of 32 bits are 1)
System.out.println((byte)0xFF);      // -1. (all 8 of 8 bits are 1)
System.out.println((int)(byte)0xFF); // -1. (all 32 of 32 bits are 1)

Note that by casting to byte and back to int, we cause all 32 bits to be 1. Hence, the following code does what you want (note there's an implicit cast to int after the explicit cast to byte):

public static void main(String[] args) {
    byte b = -1;
    System.out.println(String.valueOf(b) + " and " + String.valueOf(b & (byte)0xFF)));
}

Output:

-1 and -1

Upvotes: 2

Nick Silvestri
Nick Silvestri

Reputation: 321

0xFF is equal to an int with the value of 255, or 00000000 00000000 00000000 11111111. A byte -1 is 11111111, and because it is signed, this is interpreted as -1. If it was unsigned, this would also be 255.

When you & the two values, Java will return the result in the type of the larger of the two values, which is int, so the final result is an int with bits 00000000 00000000 00000000 11111111, which evaluates to 255.

Upvotes: 4

Related Questions