Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a hex string to a byte in Java [closed]

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");
like image 591
phpscriptcoder Avatar asked Sep 23 '09 16:09

phpscriptcoder


People also ask

How do you convert hex to bytes?

To convert hex string to byte array, you need to first get the length of the given string and include it while creating a new byte array. byte[] val = new byte[str. length() / 2];

How do you convert a hex string to a byte array?

To obtain a string in hexadecimal format from this array, we simply need to call the ToString method on the BitConverter class. As input we need to pass our byte array and, as output, we get the hexadecimal string representing it. string hexString = BitConverter. ToString(byteArray);

Is hex a 1 byte?

Each Hexadecimal character represents 4 bits (0 - 15 decimal) which is called a nibble (a small byte - honest!). A byte (or octet) is 8 bits so is always represented by 2 Hex characters in the range 00 to FF.

How do you turn a string into a byte?

We can use String class getBytes() method to encode the string into a sequence of bytes using the platform's default charset. This method is overloaded and we can also pass Charset as argument.


1 Answers

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);
like image 149
Roi A Avatar answered Oct 18 '22 20:10

Roi A