How do I convert from big integer to a byte array which is not in 2’s complement format. Bascially I only need to convert positive numbers and do not need the sign bit.
So something like 10 would become a byte 0x0a i.e-> 00001010
[Update]
As per comment I tried this
public void testBinary()
{
BigDecimal test = new BigDecimal(35116031);
BigInteger theInt = test.unscaledValue();
byte[] arr = theInt.toByteArray();
System.out.println(getCounterVal(arr, new BigInteger("256")));
}
public BigInteger getCounterVal(byte[] arr, BigInteger multiplier)
{
BigInteger counter = BigInteger.ZERO;
for(int i = (arr.length - 1); i >=0; i--)
{
int b = arr[i];
//int val = (int) b & 0xFF;
BigInteger augend = BigInteger.valueOf(b);
counter = counter.add(augend.multiply(multiplier.pow(i)));
}
return counter;
}
The out put value I got was -19720446 And with the //int val = (int) b & 0xFF; uncommented and used as augend, I got the value 4292024066
[Update2]
Here is a test I ran which works. Not sure if it is bug free but looks fine.
@Test
public void bigIntegerToArray()
{
BigInteger bigInt = new BigInteger("35116444");
byte[] array = bigInt.toByteArray();
if (array[0] == 0)
{
byte[] tmp = new byte[array.length - 1];
System.arraycopy(array, 1, tmp, 0, tmp.length);
array = tmp;
}
BigInteger derived = BigInteger.ZERO;
BigInteger twofiftysix = new BigInteger("256");
int j = 0;
for (int i = array.length - 1; i >= 0; i--)
{
int val = (int) array[i] & 0xFF;
BigInteger addend = BigInteger.valueOf(val);
BigInteger multiplier = twofiftysix.pow(j);
addend = addend.multiply(multiplier);
derived = derived.add(addend);
j++;
}
Assert.assertEquals(bigInt, derived);
}
The difference is largely conceptual. Unsigned numbers are the same in 2’s compliment. 2’s compliment just describes how to represent negative numbers which you say you don’t have.
i.e. 10 is 00001010 in signed and unsigned representation.
To get the bytes from a BigDecimal or BigInteger you can use the methods it provides.
prints
The bytes are correct and reproduce the same value.
There is a bug in the way you rebuild your BigInteger. You assume the byte serialization is little endian when Java typically uses big endian http://en.wikipedia.org/wiki/Endianness