字符串数组来六角阵列(JAVA) [英] String array to Hex Array (Java)
问题描述
我有一个实际上是由十六进制字符的字符串数组。
I have a String array that actually consists of Hex characters.
让我们说的内容 - >
Let's say the contents are ->
String array[] = {8C,D9,26,1D,69,B7,96,DB};
现在我想这是作为PTED 1个字节的十六进制字符每个,而不是作为一个字符串,其中每个条目为2个字节。除$ P $
Now I want these to be interpreted as Hex characters of 1 byte each and not as a String where each entry is 2 bytes.
StringBuilder output = new StringBuilder();
for (int j = 0; j < array.length; j++) {
String temp = "\u00"+ array[j];
output.append(temp);
}
试过类似的东西,而是因为它一直在抱怨非法UNI code转义这是不可能的。我尝试使用\\ U00(即ü前两个反斜杠,但计算器只能显示一个有),而不是\\ U00要解决这个问题的错误,但我没有看到数组中的真正的十六进制值,而不是我看到一堆像琴弦 - >\\ U008C,\\ U00D9等。
Tried something like that, but it's not possible because it keeps complaining about "illegal unicode escape". I tried using "\u00" (i.e. two backslashes before u, but stackoverflow displays only one there) instead of "\u00" to get around that error, but then I don't see the real Hex values in the array, instead I see a bunch of strings like -> "\U008C" , "\U00D9" and so on..
我想转换后的值是0x8C,0xD9,值为0x26 ...
I want the after conversion values to be 0x8C, 0xD9, 0x26...
感谢。
编辑:我已经更新的问题,我只想澄清有数组本身没有逗号。而最终我需要把所有这些值加在一起,并使用它作为一个HMAC密钥是一个十六进制字符串而不是一个文本字符串。
I have updated the question, just to clarify there were no commas in the array itself. And eventually I need to put all those values together, and use that as a HMAC key that is a hex string and NOT a text string.
推荐答案
让JDK为你做的工作:
Let the JDK do the work for you:
String[] array = {"8C", "D9", "26", "1D", "69", "B7", "96", "DB"};
StringBuilder output = new StringBuilder();
for ( String hex : array ) {
output.append( (char)Integer.parseInt( hex, 16 ) );
}
基本上只是循环内一行是你所需要的。
Basically just that one line inside the loop is all you need.
如果你想你的投入只是一个大的字符串(这似乎更方便),只是这样做,而不是:
If you wanted your input to be just one big String (which would seem more convenient), just do this instead:
String input = "8CD9261D69B796DB";
StringBuilder output = new StringBuilder();
for ( String hex : input.replaceAll( "..(?!$)", "$0," ).split( "," ) ) {
output.append( (char)Integer.parseInt( hex, 16 ) );
}
编辑:
如果你想的byte []的结果,这样做:
Edited:
If you want byte[] result, do this:
String[] array = {"8C", "D9", "26", "1D", "69", "B7", "96", "DB"};
byte[] bytes = new byte[array.length];
for ( int i = 0; i < array.length; i++ ) {
bytes[i] = (byte)Integer.parseInt( array[i], 16 );
}
这篇关于字符串数组来六角阵列(JAVA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!