Android Java CRC十六进制输入

时间:2015-05-19 13:02:08

标签: java android crc

我在使用十六进制值的crc-calculator时遇到了一些麻烦。 事实上,我有这个很好的代码,可以用ASCII输入正确计算。

但是我需要计算的六角形" 44007A0004 ..."无法转换为ASCII字符。如何更改我的函数来计算十六进制输入字符串crc?

 public String  CRC_CCITT( int flag,String str)  {   
         int crc = 0x00;          // initial value  
         int polynomial = 0x1021;     
         byte[] bytes = str.getBytes();

    switch(flag){  
    case 1:  
        crc=0x00;  
        break;  
    case 2:  
        crc=0xFFFF;  
        break;  
    case 3:  
        crc=0x1D0F;  
        break;  

    }  
    for (int index = 0 ; index< bytes.length; index++) {  
        byte b = bytes[index];  
        for (int i = 0; i < 8; i++) {  
            boolean bit = ((b   >> (7-i) & 1) == 1);  
            boolean c15 = ((crc >> 15    & 1) == 1);  
            crc <<= 1;  
            if (c15 ^ bit) crc ^= polynomial;  
         }  
    }  
    crc &= 0xffff;  
    str = Integer.toHexString(crc);  
    return str;            
}    

1 个答案:

答案 0 :(得分:0)

参考这个答案:

Convert a string representation of a hex dump to a byte array using Java?

hexStringToByteArray函数添加到您的代码中,并按以下方式调用它:

byte[] bytes = hexStringToByteArray(str);