This week's book giveaway is in the Java 8 forum.
We're giving away four copies of Java 8 in Action and have Raoul-Gabriel Urma, Mario Fusco, and Alan Mycroft on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Binary Numbers Comparison. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Binary Numbers Comparison." Watch "Binary Numbers Comparison." New topic
Author

Binary Numbers Comparison.

Nathan Heimdall
Greenhorn

Joined: Mar 02, 2009
Posts: 20
Hello all ,

I have two arbitrary length binary numbers.
ex : 100011111 & 1111001110001
Is it possible to compare them using only there 0s & 1s representations.
i.e I don't want to convert them to base 10 & compare them (probably using BigInteger).

If its possible how can I implement it
Thanks.


-Nathan
"A single conversation with a wise man is better than ten years of study."
K. Tsang
Bartender

Joined: Sep 13, 2007
Posts: 1977
    
    7

You don't have to convert to decimals. Every bit is 2^x so you at least need to find the bits that are 1 and calculate what x is for that bit. Without converting to decimal I think the faster way to get the most significant bit that is 1 of each number and compare that. Oh you do need to watch out for negatives (such as first bit is 1).

K. Tsang JavaRanch SCJP5 SCJD/OCM-JD OCPJP7
Piet Verdriet
Ranch Hand

Joined: Feb 25, 2006
Posts: 266
Heimdall Ksu wrote:Hello all ,

I have two arbitrary length binary numbers.
ex : 100011111 & 1111001110001
Is it possible to compare them using only there 0s & 1s representations.


How are you storing these numbers? As Strings?

Heimdall Ksu wrote:i.e I don't want to convert them to base 10 & compare them...


In Java, all numbers are in base 10. Yes, you can use octal or hexadecimal literals, but their value will still be stored as a decimal (base 10).
Steve Fahlbusch
Bartender

Joined: Sep 18, 2000
Posts: 557
    
    7

In Java, all numbers are in base 10. Yes, you can use octal or hexadecimal literals, but their value will still be stored as a decimal (base 10).


Didn't you mean that all numbers (ie: numeric primitives) are stored in binary and then by default formattted for output as decimal?
Nathan Heimdall
Greenhorn

Joined: Mar 02, 2009
Posts: 20
Yes I am storing them as strings.
I padded them to equal length and then used the compare function in String class and got the result I was looking for.

Thanks guys,
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36598
    
  16
I suspect String.compareTo works as much from luck as anything else
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Binary Numbers Comparison.
 
Similar Threads
Outputing Binary Numbers
Binar representation of octal & hexadecimal nos
hexadecimal?
compare two very large binaries
binary file comparison