I want to put a string value to an array byte without any conversion.
the string length is always 14 and it's in fact an hexadecimal value presenting the date and time. so every 2 chars in this string is a byte so my byte array is a 7 bytes length.
i didn't find a way to do so.
the string.getBytes() method is doing a conversion.
i tryed this method also https://stackoverflow.com/a/11208685/3343174 but after debugging it's showing a different values from the first string.
2 Answers
You can get a substring of two chars of your string like this:
String yourString = "07df";
String firstByteAsString = yourString.substring(0,2); // start - end(excl.)
// = "07"
You can get a byte from this like this:
byte b = Byte.parseByte( firstByteAsString, 16 );
I am sure, you'll manage to use this to get your desired functionality.
EDIT As Peter points out: Values > 127 are a Problem. So you'll actually have to use
byte b = (byte) (Integer.parseInt( firstByteAsString, 16) & 0xFF);
But his answer is much simpler and doing all this for you. You should go for BigInteger and accept Peter's answer.
11 Comments
df is > 127 and cannot be parsed as a byte.Lets assume you want to convert a hexidecimal string into byte[]. e.g. you have 14 characters in hexidecimal and you want to convert this to bytes where two character represent each byte.
for example the first four chars in my string are '07df' i want that the 2 first bytes in my byte array contain respectively '07' and 'df'
String base16 = "07df07df07df07";
byte[] bytes = new BigInteger(base16, 16).toByteArray();
if (bytes[0] == 0)
bytes = Arrays.copyOfRange(bytes, 1, bytes.length);
System.out.println(Arrays.toString(bytes));
prints
[7, -33, 7, -33, 7, -33, 7]
I want to get [07, df, 07, df, 07, df, 07]
This is a matter of formatting the byte[] in the form you want. (byte) 0xDF is -33 Numbers are just numbers, they don't remember the format you used to create them, they just have one default format and if you don't like, it you can add your own.
StringBuilder sb = new StringBuilder();
String sep = "[";
for (byte b : bytes) {
sb.append(sep).append(String.format("%02x", b & 0xFF));
sep = ", ";
}
sb.append("]");
System.out.println(sb);
prints
[07, df, 07, df, 07, df, 07]
8 Comments
(byte) 0xdf is -33 if you can change the way it is printed if you want hexidecimal.
String. Once you have some code ready and if you run into trouble, then the community will help you fix it.Ahas a byte value of65. You understand that the numeric value ofAas a hexadecimal digit is different to the value ofAis achar?