I want to convert string to byte array like below:
If I have a string:
String str = "0x61";
I want it as:
byte[] byteArray = {0x61};
Any idea?
I don't really know what you are trying to achieve. Can you elaborate on your use case?
I believe what you want is
str.getBytes();
if your string doesn't have 0x before every digit, then this method will perform the conversion:
private byte[] generateByteArray(String byteArrayStr)
{
byte[] result = new byte[byteArrayStr.length() / 2];
for (int i = 0; i < byteArrayStr.length(); i += 2)
{
result[i / 2] = (byte)((Character.digit(byteArrayStr.charAt(i), 16) << 4) + Character.digit(byteArrayStr.charAt(i + 1), 16));
}
return result;
}
This method will transform "FF00" into {255, 0}
You will need to make sure that the length of the String is even, since every 2 digits will constitute 1 byte (in hex format).