Re: convert byte array to hex string using BigInteger
On 6/26/2013 10:12 PM, Arne Vajh?j wrote:
On 6/20/2013 8:03 AM, Laura Schmidt wrote:
I try to convert a byte array to a hex string like this:
private static String hex_encode (byte [] val)
{
BigInteger b = new BigInteger(val);
String t = b.toString(16);
return (t);
}
For a long byte array it returns a "negative" hex string, i. e. starting
with a "-" sign.
But I want just the bytes in the array converted to hex representation,
each one ranging from "00" to "FF". There should be no minus sign then.
You have already received several working solutions.
I will strongly recommend you drop the idea about using
BigInteger for this.
It becomes extremely tricky to get it right - you have already
found the sign problem - next problem will be the leading zero
problem.
One of the problems is that toString(radix) and toHexString()
are not the same method.
Demo:
public class SimpleHex {
public static void main(String[] args) {
for(int i = -1; i <= 1; i++) {
System.out.println(Integer.toString(i, 16));
System.out.println(Integer.toHexString(i));
}
}
}
Arne