0

I want to convert decimal -10 value to hex in a String and byte array format.

I have tried

String minHex = Integer.toHexString(Integer.valueOf(-10));
System.out.println(minHex);

Which results in fffffff6, and I think it is not correct. And for converting byte array I am using below function which I found from

Convert a string representation of a hex dump to a byte array using Java?

public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                                 + Character.digit(s.charAt(i+1), 16));
        }
        return data;
}

So also not sure it will work for minus hex value or not.

Community
  • 1
  • 1
commit
  • 4,777
  • 15
  • 43
  • 70
  • your result is in twos complement form - do this (0000 0000 0000 0000 0000 0000 0000 1010) binary of 10 considering a 32 bit integer you have. Now take the inverse of all the digits (1111 1111 1111 1111 1111 1111 1111 0101) and add 1 to the result. You will get what you got above fffffff6. It is signed. – ha9u63a7 Nov 06 '14 at 12:29

1 Answers1

0

To convert an hex to a String the way you expect it i.e. -10 is converted to -a, use:

String hex = Integer.toString(-10, 16);

To convert to a byte array, simply convert the int to a byte array, it is represented the same way:

byte[] bytes = ByteBuffer.allocate(4).putInt(-10).array();
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118