简体   繁体   English

如何在Java中将字符串转换为十六进制字节

[英]How to convert string to hex bytes in Java

I want to split each of two chars in string and convert it to hex byte array representation, i am just lost how to do this. 我想将两个字符中的每个字符拆分为字符串并将其转换为十六进制字节数组表示形式,我只是迷路了。

in string a= hex a which is 10 in decimal in string b= hex b which is 11 in decimal 在字符串a =十六进制a中,十进制为10在字符串b =十六进制b中,十进制为11

String toConvert = "abbbbbbbbbbbbbbbbbbbbbbc";
byte[] output = new byte[12];





                          Input
 ab    bb   bb    bb  bb   bb   bb   bb   bb   bb   bb   bc
                          output
[-85, -69, -69, -69, -69, -69, -69, -69, -69, -69, -69, -68]

Takes the first character in a group of two, multiplies its hex value by 16 (it's in the 16 1 place). 以两个为一组的第一个字符,将其十六进制值乘以16 (在16 1位)。 That result is added to the second character's hex value. 该结果将添加到第二个字符的十六进制值。

String toConvert = "abbbbbbbbbbbbbbbbbbbbbbc";
byte[] output = new byte[toConvert.length() / 2];

for (int i = 0; i < output.length; i++) {
    output[i] |= Character.digit(toConvert.charAt(i * 2), 16) * 16;
    output[i] |= Character.digit(toConvert.charAt(i * 2 + 1), 16);
}

Apache Common Codec's Hex class does exactly what you need: Apache Common Codec的Hex类完全满足您的需求:

byte[] bytes = Hex.decodeHex("abbbbbbbbbbbbbbbbbbbbbbc".toCharArray());

If you can't/won't use third parties, you can always "borrow" their implementation (slightly simplified - I omitted correctness checks for simplicity): 如果您不能/不使用第三方,则可以随时“借用”第三方的实现(略有简化-为简单起见,我省略了正确性检查):

public static byte[] decodeHex(final char[] data) {

  final int len = data.length;

  // Handle empty string - omitted for clarity's sake

  final byte[] out = new byte[len >> 1];

  // two characters form the hex value.
  for (int i = 0, j = 0; j < len; i++) {
      int f =  Character.digit(data[j], 16) << 4;
      j++;
      f = f | Character.digit(data[j], 16);
      j++;
      out[i] = (byte) (f & 0xFF);
  }

  return out;
}
for(int i = 0; i < 12; i++) {
    output[i] = (byte) Integer.parseInt(toConvert.substring(i*2, i*2+2), 16);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM