ChkSum(int len, char* buf, char* res)
{
    int i;
    memset(res, 0, 8);
    for(i=0; i<len; i+=4)
    {
        res[0]^=(buf+i)[0];
        res[1]^=(buf+i)[1];
        res[2]^=(buf+i)[2];
        res[3]^=(buf+i)[3];
    };    res[0]=~res[0];
    res[1]=~res[1];
    res[2]=~res[2];
    res[3]=~res[3];    // 将16进制数扩展为对应字符串(如0xE8--->"E8")
    for(i = MSG_CHKSUM_LEN-1; i >= 0; i --)
    {
        if ( i % 2 ) // LOW
        {
            res[i] = (res[i/2] & 0x0F) + '0';
            if ( res[i] > '9' )
            {
                res[i] = res[i] + 'A' - '0' - 10;
            }
        }
        else // HIGH
        {
            res[i] = ((res[i/2] >> 4) & 0x0F) + '0';
            if ( res[i] > '9' )
            {
                res[i] = res[i] + 'A' - '0' - 10;
            }
        }
    }
}
转完验证后,立即结帖!

解决方案 »

  1.   

    UP   UP UP UP UP
      

  2.   

    这是计算校验和的C程序,意思是按4个字节依次异或,最后结果取反。再把最后的结果转成16进制。我写了一部分,但是最终计算出结果不正确。
    public void computeCheckSum(byte[] arr) {
    System.out.println("checksum string=" + new String(arr));
    byte[] b = arr;
    byte[] res = new byte[4];
    for (int i = 0; i < b.length; i += 4) {
    res[0] ^= b[i];
    res[1] ^= b[i + 1];
    res[2] ^= b[i + 2];
    res[3] ^= b[i + 3];
    }
    res[0] = (byte) ~res[0];
    res[1] = (byte) ~res[1];
    res[2] = (byte) ~res[2];
    res[3] = (byte) ~res[3];
             for (int i = 0; i < 4; i++) {
        System.out.print(byte2hex(res[i])+"--");
    }
    }
    public static String byte2hex(byte b) {
    StringBuffer buf = new StringBuffer();
    char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    int high = ((b & 0xf0) >> 4);
    int low = (b & 0x0f);
    buf.append(hexChars[high]);
    buf.append(hexChars[low]);
    return buf.toString();
    }