【发布时间】:2015-05-27 20:53:32
【问题描述】:
我正在开发使用 SIP2 协议 (https://en.wikipedia.org/wiki/Standard_Interchange_Protocol) 的图书馆系统的 REST 接口,并且能够在不需要纠错的系统上正常工作。但是,我的代码现在正在与另一个需要校验和的系统通信,规范中如此描述:
“要计算校验和,请将每个字符添加为无符号二进制数,取总数的低 16 位并执行 2 的补码。校验和字段是由四个十六进制数字表示的结果。”
我对此进行了几次运行,但无论我做什么,我都无法获得与我的示例消息匹配的校验和。我可能比它应该做的更难(似乎在具有适当二进制类型的低级语言中更容易,等等)。这是我最近的尝试:
var checksum = 0;
var message = "63AOAA21221021780249|AD9999|AY0AZ";
// add each character as an unsigned binary number
for(var i=0;i<message.length;i++){
checksum += message[i].charCodeAt();
}
console.log("character sum: " + checksum);
// take the lower 16 bits of the total
checksum = checksum.toString(2);
console.log("character sum binary representation: " + checksum);
while(checksum.length < 16){
checksum = "0" + checksum;
}
checksum = checksum.substr(0,16);
console.log("lower 16 bits of character total: " + checksum);
// convert to dec
checksum = parseInt(checksum,2);
console.log("checksum dec: " + checksum);
// perform 2's complement
checksum = (checksum & 0xFFFF) * -1;
console.log("2s complement: " + checksum.toString(2));
// convert to 4 hex digits
checksum = dec2hex(checksum);
console.log("checksum hex: " + checksum);
function dec2hex(i) {
return (i+0x10000).toString(16).substr(-4).toUpperCase();
}
上述字符串的预期校验和是“F39A”。
【问题讨论】:
标签: javascript checksum