互联网校验和中的位移 [英] Bit shifting in internet checksums
问题描述
这几乎肯定是一个非常愚蠢的问题,但是由于某些原因,我无法进行Internet校验和计算.所有的算法基本上都是这样的:
This is almost certainly a very silly question, but for some reason I'm having trouble with internet checksum calculations. All of the algorithms basically look something like this:
WORD chksm(WORD *startpos, WORD checklen){
ulong sum = 0;
WORD answer = 0;
while (checklen > 1)
{
sum += *startpos++;
checklen -= 2;
}
if (checklen == 1)
{
*(BYTE *)(&answer) = *(BYTE *)startpos;
sum += answer;
}
sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
answer = ~sum;
return answer;}
我清楚除了行外的所有内容:
I'm clear on everything except for the line:
sum += (sum >> 16);
看起来像紧接在前16位的前16位中的所有行一样,在前16位中保留所有零的行.如果真是这样,那么总和>> 16现在不等于零吗?如果是这样,为什么那条线在那里?
It looks like the line immediately before it adds the top 16 bits to the bottom 16 bits, leaving all zeroes in the top 16 bits. If that's the case, then wouldn't sum >> 16 now be equal to zero? And if so, why is that line there?
或者我今天(可能)只是完全精神衰竭?
Or am I (likely) just having a complete mental failure today?
推荐答案
您几乎是正确的.
由于进位,高16位可能为1.
The high 16 bits could have been 1 due to a carry.
例如FFFF + FFFF => 1FFFE
或FFFF + 1 => 10000
.
这篇关于互联网校验和中的位移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!