Reputation: 51
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
Reputation: 135992
try DatatypeConverter.parseHexBinary(str)
from javax.xml.bind
package
Upvotes: 1
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