12

In Java, how can a hexadecimal string representation of a byte (e.g. "1e") be converted into a byte value?

For example:

byte b = ConvertHexStringToByte("1e");
GaspardP
  • 4,217
  • 2
  • 20
  • 33
phpscriptcoder
  • 717
  • 2
  • 9
  • 22

3 Answers3

23

You can use Byte.parseByte("a", 16); but this will work only for values up to 127, values higher then that will need to cast to byte, due to signed/unsigned issues so i recommend to transfer it to an int and then cast it to byte

(byte) (Integer.parseInt("ef",16) & 0xff);
Roi A
  • 231
  • 2
  • 3
14
Integer.parseInt(str, 16);
skaffman
  • 398,947
  • 96
  • 818
  • 769
ZZ Coder
  • 74,484
  • 29
  • 137
  • 169
12

Byte.parseByte will return a byte by parsing a string representation.

Using the method with the (String, int) signature, the radix can be specified as 16, so one can parse a hexadecimal representation of a byte:

Byte.parseByte("1e", 16);
coobird
  • 159,216
  • 35
  • 211
  • 226
  • 8
    Danger! This method will fail to parse negative byte values, for example, "AD". See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6259307 . Better to use Integer.parseInt – Dave L. May 28 '10 at 16:31
  • 1
    @Dave L. That is not correct because according to evaluator: The method in question is behaving exactly as specified. With this method a negative value must be indicated by using a minus sign "-" and not be setting the sign bit by having the high order bit be one. In other words, for base 16 the valid strings range from "-80" (-128) to "7f" (127); "AD" base 16 is positive 173 which is out of range. – Caner Nov 29 '11 at 11:38
  • 1
    @LAS_VEGAS Indeed Byte.parseByte performs as specified, however if someone wants to convert a 2 character hex representation of an 8-bit value to the corresponding byte, as implied by the questioner, then this method (as specified and implemented!) will not do that for values where the high order bit is 1. – Dave L. Nov 29 '11 at 17:37
  • 1
    Got any comments on parsing negative bytes Dave? – Shark Aug 29 '12 at 16:18