Rob van Dijk
Rob van Dijk

Reputation: 722

Convert byte array represented as hexadecimal string to correct int

I have a byte array,

[102, 100, 51, 52, 48, 48]

Which has the hex string representation:

"fd3400"

Which if I convert it to a number, shows as being 16593920.

However, when I convert it using the snippet below

int iSec = ByteBuffer.wrap(bSec).order(ByteOrder.LITTLE_ENDIAN).getInt();

I get the result: 875783270. The bytes are supposed to be in LSB format, but I can't seem to get the correct value out, as 875783270 != 16593920. I'm getting kind of confused with these data formats.

Upvotes: 1

Views: 466

Answers (1)

damjad
damjad

Reputation: 1290

Byte array contains the byte representation of a string.

In ASCII:

  • 102 == 'f'
  • 100 == 'd'
  • 51 == '3'
  • 52 == '4'
  • 48 == '0'

You should convert from byte array to string and then parse that string using base 16 (hexadecimal).

String hex = new String(arr, "ASCII"); //fd3400
int number = Integer.valueOf(hex, 16).intValue(); //16593920

Upvotes: 3

Related Questions