读书人

急求!对消息异或取反生成4Byte校验和

发布时间: 2012-06-14 16:00:31 作者: rapoo

急求!!!对消息异或取反生成4Byte校验和,下面是C实现的源码,求高手转化成java代码实现,小弟在此谢谢了,20分全部奉上
实现检验和的C语言源码(AAA格式):
/*************************************************
Function: GetChkSum
Description: 实现对“消息头 + 会话头 + 事务头 + 操作信息”按32位异或

Calls:
Called By:
Input: len是指“消息头 + 会话头 + 事务头 + 操作信息”四者的长度和。

Buf是指“消息头 + 会话头 + 事务头 + 操作信息”四者结合的字符数组。

Output: res是指按32位异或得到的结果
Return:
Others:
*************************************************/
void GetChkSum(Int len, PSTR buf, PSTR res)
{
memset(res, 0, 4); //AAA格式的校验码为4字节
for(int 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];
}

[解决办法]
看看这个符不符合你要求

Java code
public class ValidateTest{    public static void main(String[] args)    {        ValidateTest t = new ValidateTest();        String s = "abcdefghijklmnopqrstuvwxyz12345678987654321";        byte[] buf = t.getBuffer(s);        byte[] res = new byte[4];        t.getChkSum(buf.length, buf, res);    }    byte[] getBuffer(String s)    {        byte[] buf = s.getBytes();        int len = buf.length;        int temp = 0;        if (len % 4 != 0)        {            temp = 4 - len % 4;        }        byte[] buf1 = new byte[len + temp];        System.arraycopy(buf, 0, buf1, 0, len);        return buf1;    }    void getChkSum(int len, byte[] buf, byte[] res)    {        for (int i = 0; i < len; i += 4)        {            res[0] ^= buf[0 + i];            res[1] ^= buf[1 + i];            res[2] ^= buf[2 + i];            res[3] ^= buf[3 + i];        }        res[0] = (byte) ~res[0];        res[1] = (byte) ~res[1];        res[2] = (byte) ~res[2];        res[3] = (byte) ~res[3];    }} 

读书人网 >Java相关

热点推荐