Sat
Sat

Reputation: 51

convert string with hexa to byte

I've a String with value 0xE20x800x93. I try to convert them like this and it works

byte[] bs = new byte[]{
(byte) 0xE2,(byte) 0x80, (byte) 0x93
}; 

But what I want is without doing the explicit casting, I need to convert it into a byte array.

Or at least a way to convert into a byte object, and not a byte[] object.

Upvotes: 1

Views: 170

Answers (2)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

try DatatypeConverter.parseHexBinary(str) from javax.xml.bind package

Upvotes: 1

Bohemian
Bohemian

Reputation: 424973

You can do it in one (albeit long) line:

byte[] bytes = Arrays.copyOfRange(new ByteBuffer().putInt(Integer.parseInt(str.replace("0x", ""), 16)).array(), 1, 4);

This assumes you have exactly 3 bytes to get. If it's a variable length, the following code is more generic, but slightly more verbose, because it uses the length of the input to determine the eventual result size:

byte[] bytes = Arrays.copyOfRange(new ByteBuffer().putInt(Integer.parseInt(str.replace("0x", ""), 16)).array(), 4 - str.length() / 4, 4);

Upvotes: 2

Related Questions