0

I got a hexstring like "0xFF" and would like to convert the string to byte 0xFF, because an other function needs the value as hexbyte. So something like this:

         String hexstring="0xFF";
         //convert to byte
         byte hexbyte = (byte) 0xFF;

Thanks for helping

  • 3
    Possible duplicate of [In Java, how do I convert a hex string to a byte\[\]?](http://stackoverflow.com/questions/8890174/in-java-how-do-i-convert-a-hex-string-to-a-byte) – Jessie Mar 30 '17 at 01:17

2 Answers2

0

(byte) (Integer.parseInt("ef",16) & 0xff);will work for you

Jiahao Cai
  • 1,222
  • 1
  • 11
  • 25
  • My Question is not how to convert to decimal-byte, but to hex-byte. So your code gives me a certain decimalnumber where I need a hex-byte. – Peter Lustig Mar 31 '17 at 11:43
0
public static byte[] asByteArray(String hex) {
    // Create a byte array half the length of the string.
    byte[] bytes = new byte[hex.length() / 2];

    // Repeat the process for the number of elements in the byte array.
    for (int index = 0; index < bytes.length; index++) {
        // Convert hexadecimal string to bytes and store in array.
        bytes[index] =
            (byte) Integer.parseInt(
                hex.substring(index * 2, (index + 1) * 2),
                16);
    }

    // return byte array。
    return bytes;
}
oza
  • 51
  • 1
  • 1
  • 9