Why does bitwise AND with byte in JAVA do this?
bit, bit-manipulation, byte, char, java
Solution
The literals in Java are in the form of `int`. So when you say `-20 & 0xFF`, this is what happens:
11111111 11111111 11111111 11101100 //-20 -ve nos are stored in 2's compliment form
& 00000000 00000000 00000000 11111111 // 0xFF
-------- -------- -------- --------
00000000 00000000 00000000 11101100 // 236
Since the negetaive values are stored in 2's compliment form, you get the value 236.
When you perfrom `20 & 0xFF`, this happens:
00000000 00000000 00000000 00010100 // 20 -ve nos are stored in 2's compliment form
& 00000000 00000000 00000000 11111111 // 0xFF
-------- -------- -------- --------
00000000 00000000 00000000 00010100 // 20
Problem
I'm messing around with bitwise operators, and I was trying to convert a negative byte to an unsigned 8 bit value, and this is what people suggested: ``` System.out.println(-20 & 0xFF); //bitwise AND on negative number and 255 ``` So, this works perfectly, and returns 236, but why? As far as I'm concerned: ``` 00010100 //binary representation of -20 11111111 //binary representation of 0xFF or 255 -------- 00010100 //it returns the same exact thing, so it's either -20 or 20 ``` Why does it work? I think I've missed something pretty simple, but I can't seem to grasp it. Also, if I do it with a positive number below 256, it returns the same number. I can't seem to understand what Java does with these numbers.