File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Binary in Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Binary in Java" Watch "Binary in Java" New topic
Author

Binary in Java

Siva kandasamy
Ranch Hand

Joined: Dec 31, 2002
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

Thnaks for your help.
siva
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

What's your question exactly?


[Jess in Action][AskingGoodQuestions]
Siva kandasamy
Ranch Hand

Joined: Dec 31, 2002
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

Joined: Mar 18, 2003
Posts: 281

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!
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.
 
 
subject: Binary in Java