Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Binary in Java

Siva kandasamy
Ranch Hand
Posts: 139
Hi there,
Please see my code and its output.
Can you tell me how binary is represented in Java.
My understanding is, in byte, binary is represented as "1111"
ie. 1111 = -1
where as java prints "-1" for -1
and for -7 it prints "-111".

~/rd/java/binary % java URShift
-7: -111
-1: -1

siva

Ernest Friedman-Hill
author and iconoclast
Marshal
Posts: 24212
35

Siva kandasamy
Ranch Hand
Posts: 139
Sorry for the confusion.
Look at my code in my previous posting.
My question is,
why Java prinits -111 in binary for -7 instead of
"1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1001"
Here my understaning is JVM is 64 bit and -7 is represented in binary as I quoted above.

thanks
siva
[ February 06, 2004: Message edited by: Siva kandasamy ]

Eddie Vanda
Ranch Hand
Posts: 283

I haven't looked at the Integer.toString method but for decimal it prints the sign followed by the absolute positive value. Similarly, for base 2 (binary) it prints the sign before the absolute positive value in binary.
If you take the two's complement of your long number by inverting all the bits and adding one, you get 111 base 2, which is positive 7!
So the Integer.toString method is consistent between different number bases.

Ernest Friedman-Hill
author and iconoclast
Marshal
Posts: 24212
35
Yes, what Eddie said. This method doesn't promise to print the binary representation of a number; it prints the "base X" representation of a number if you pass in "X" as the second argument. It uses a minus sign followed by a magnitude to represent negative numbers.
Note also that we're not talking about what "Java" does, but what the "Integer.toString" method does. If you look a bit more closely at the API document for java.lang.Integer, you'll find "toBinaryString()", a method which does what you want.
Note also that the statement "Java is 64 bit" is incorrect, or at least meaningless -- Java ints are 32 bit, signed, but the JVM implementation itself is abstract and can be 32-bit, 64-bit or anything else.