Jasmine
Jasmine

Reputation: 155

Convert Integer to Hex-> LittleEndian format in Java

I am trying to get the Little Endian format value in Hex(in Java) for my code but getting fffff in the first digit and not getting the value similar to what this site returns: https://www.rapidtables.com/convert/number/decimal-to-hex.html

Here is the code:

private static void convertToHex() {

    String hextestValue = Integer.toHexString(1234);
    int value = Integer.parseInt(hextestValue, 16);
    ByteBuffer bb = ByteBuffer.allocate(4);
    bb.order(ByteOrder.LITTLE_ENDIAN);
    bb.putInt(value);
    System.out.print("x = ");
    for (byte b : bb.array()) {
        System.out.printf("%2s", Integer.toHexString(b) + " ");
    }

}

Not sure what needs to be done to return the result in similar format.

e.g. for input 1234 I need the output: D2 04

Upvotes: 0

Views: 547

Answers (2)

bvdb
bvdb

Reputation: 24710

In addition to the other answer of @g00se,

It may also be worth noting that an int consumes 4 bytes in java. For that reason you are forced to allocate 4 bytes in your example.

However, a short is only 2 bytes.

ByteBuffer bb = ByteBuffer.allocate(2);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.putShort((short)value);

That will get rid of the unnecessary bytes.

Upvotes: 0

g00se
g00se

Reputation: 4296

System.out.printf("%02X ", b);

Is what you need

Upvotes: 1

Related Questions