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".
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.
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.
The nice thing about Standards is that there are so many to choose from!
author and iconoclast
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.