Haitham Sakr
Haitham Sakr

Reputation: 103

some thing wrong with array index in byte[]

I have string like this

String text = "f001050000000000003d61c1c1df400200c0000009181600ef014000003f20"

I converted it to bytes to loop through it as bytes

byte[] bytes = new BigInteger(text,16).toByteArray();        
    for (int i = 0; i < bytes.length; i++) 
    {            
        System.out.print(String.format("%02x ", bytes[i]));
    }

But when I print array values it adds byte 00 at the beginning of the actual string! It should start with f0 but it starts with 00!

When I start index with 1 this 00 disappear. From where this 00 come!?

Upvotes: 0

Views: 107

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136042

I think BigInteger is no good for this task. You need to parse your text yourself, it's not difficult

    byte[] bytes = new byte[text.length() / 2];
    for (int i = 0; i < bytes.length; i++) {
        bytes[i] = (byte) ((Character.digit(text.charAt(i * 2), 16) << 4) + Character.digit(text.charAt(i * 2 + 1), 16));
    }

not that it also converts "0000f0..." correctly but BigInteger would truncate leading zeroes (normalize) because for BigInteger it is just a number

Upvotes: 1

jlordo
jlordo

Reputation: 37813

JavaDoc of BigInteger#toByteArray() states:

Returns a byte array containing the two's-complement representation of this BigInteger. The byte array will be in big-endian byte-order: the most significant byte is in the zeroth element. The array will contain the minimum number of bytes required to represent this BigInteger, including at least one sign bit, which is (ceil((this.bitLength() + 1)/8)).[...]

As you have a positive number, the first bit will be zero in two's complement.

Upvotes: 4

Related Questions