So, i'm fairly new to java, and i'm a bit confused about the byte system. So I made this program that converts integers to their base two value.
class Bits
{
public static void main(String[] args)
{
byte a;
a = 5;
System.out.println(Integer.toBinaryString(a)); /* prints 101 */
a = -1;
System.out.println(Integer.toBinaryString(a)); /* prints
11111111111111111111111111111111*/
}
}
It works as expected with positive numbers, but when I enter negative numbers, it gets weird. Now I know what two's compliment is, and it doesn't say that -1
is 11111111111111111111111111111111
. It is supposed to be 11111111, right? When I change a
to an int 255
, which would be -1
as a byte, I get the normal result, 11111111
, when I switch it to binary. Can someone explain to me why this is happening, or did I do something wrong. (I am using java 8 and i'm on a mac)