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?
Are you leaving out parts of the information here? The problem you describe can be done with a simple
byte[] byteArray = {Byte.decode(str)};
If I understand your question, then you could do -
String str = "0x61";
byte[] arr = new byte[] {(byte) Integer.parseInt(str.substring(2), 16)};
System.out.println(arr[0] == 0x61);
Output is
true
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).
Step 1) Convert hex to long Step 2) Convert long to byte array.
String str = "0x61";
long l = Long.valueOf(str).longValue(); //step 1
byte[] bytes = ByteBuffer.allocate(8).putLong(l).array(); //step 2