BigInteger and its hexadecimal string representation

N

Nash

Hi All

Suppose I have 2 bigintegers b1 and b2. Is comparing the two
bigintegers using their compareTo() same as converting them to their
hexadecimal string representations and then comparing them?

For eg.

BigInteger b1 = ...;
BigInteger b2 = ...;

String hexb1 = b1.toString(16);
String hexb2 = b2.toString(16);

Is b1.compareTo(b2) equivalent to hexb1.compareTo(hexb2);

TIA
A
 
M

Mike Schilling

Nash said:
Hi All

Suppose I have 2 bigintegers b1 and b2. Is comparing the two
bigintegers using their compareTo() same as converting them to their
hexadecimal string representations and then comparing them?

For eg.

BigInteger b1 = ...;
BigInteger b2 = ...;

String hexb1 = b1.toString(16);
String hexb2 = b2.toString(16);

Is b1.compareTo(b2) equivalent to hexb1.compareTo(hexb2);

Not at all; the two may have different signs:

import java.math.*;

public class BigInt
{
public static void main(String[] args)
{
BigInteger b1 = new BigInteger("51");
BigInteger b2 = new BigInteger("257");

String s1 = b1.toString(16);
String s2 = b2.toString(16);

System.out.println(b1.compareTo(b2));
System.out.println(s1.compareTo(s2));
}
}

% java BigInt
-1
2

Since 257 > 51 but "33" > "101".
 
R

Roedy Green

Suppose I have 2 bigintegers b1 and b2. Is comparing the two
bigintegers using their compareTo() same as converting them to their
hexadecimal string representations and then comparing them?

The most important difference is two string must be the same sign and
the same length the compare lexicographically. I.e. the short one
must be padded on the left with 0s.

If you convert to String you have the overhead of converting to
String. Further you will compare more than twice as many bytes as if
you compared the BigInteger binary directly. So comparing with
BigInteger.compare will be at least ten times faster.

The difference would not be as pronounced for BigDecimal since
converting to String does not need to do repeated divisions.
--
Roedy Green Canadian Mind Products
http://mindprod.com

"Deer hunting would be fine sport, if only the deer had guns."
~ William S. Gilbert of Gilbert and Sullivan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top