getBytes没有得到正确的字节数量

时间:2013-08-05 14:00:37

标签: android string hex

我需要创建一个十六进制值字符串。现在,我有这样的事情。

String address = "5a f2 ff 1f";

但是当把这个地址变成字节时:

byte[] bytes= address.getBytes();

它将每个字母和空格作为一个字节,而不是将每个2个字符作为一个字节离开空格。所以......

我如何宣布这个?

    private String CalcChecksum (String message) {

    /**Get string's bytes*/
    message = message.replaceAll("\\s","");
    byte[] bytes = toByteArray(message);
    byte b_checksum = 0;

    for (int byte_index = 0; byte_index < byte_calc.length; byte_index++) {
        b_checksum += byte_calc[byte_index];
    }

    int d_checksum = b_checksum;  //Convert byte to int(2 byte)
    int c2_checksum = 256 - d_checksum;  
    String hexString = Integer.toHexString(c2_checksum);  

    return hexString;
}

2 个答案:

答案 0 :(得分:1)

String address = "5a f2 ff 1f";
byte[] bytes = DatatypeConverter.parseHexBinary(address.replaceAll("\\s","")).getBytes();

如前所述,你正在使用hex,你不能以你想要的方式使用.getBytes()!

答案 1 :(得分:1)

您需要指定您的字符串包含十六进制值。在下面的解决方案中,您需要在转换之前从字符串中删除所有空格:

import javax.xml.bind.DatatypeConverter;

class HexStringToByteArray {

    public static void main(String[] args) {
        String address = "5A F2 FF 1F"; 
        address = address.replaceAll("\\s","");
        System.out.println(address);
        byte[] bytes = toByteArray(address);
        for( byte b: bytes ) {
            System.out.println(b);
        }
        String string_again =  toHexString(bytes);
        System.out.println(string_again);
    }
    public static String toHexString(byte[] array) {
        return DatatypeConverter.printHexBinary(array);
    }

    public static byte[] toByteArray(String s) {
        return DatatypeConverter.parseHexBinary(s);
    }

}

这将打印(注意字节为签名):

5AF2FF1F    // Original address
90          // 5A
-14         // F2
-1          // FF
31          // 1F
5AF2FF1F    // address retrieved from byte array