I need to convert a string array
to pares hexadecimales
for each byte, zero separating each pair and completados con ceros a la izquierda
if necessary.
Using my code I get this:
41 54 2B 43 53 51 C A
But I need this:
41 54 2B 43 53 51 0C 0A
This is my code:
public class StringToHex {
public String convertStringToHex(String str) {
char[] chars = str.toCharArray();
StringBuffer hex = new StringBuffer();
for (int i = 0; i < chars.length; i++) {
hex.append( Integer.toHexString( (int) chars[i]).toUpperCase());
if (hex.length() < 2) {
hex.insert(1, '0');
}
hex.append(" ");
}
return hex.toString();
}
}
But it doesn't seem to work, can you tell me what is my mistake?
You can add a "0" when you detect that the length of the element to print is 1:
This would be done as follows:
Example :
Without the change we would get
57 31 6C 6C C 3F
but now the output would be:This is my solution.
It turns out that the condition that it is only one character that you had considered everything that you already had in
String
it, so after the first iteration it was never going to be less than 2, I solved it by comparing the converted character and verifying that it is 1, in that case then add a 0 in front and then add the valueHEX
, I hope it works for you, greetings.Try using the String.format method to do the conversion and keep the formatting according to your needs.