我已经制作了一个 8 位校验和函数,但总和没有回绕,我的意思是左边的溢出进位不会在右边加回去。我怎样才能做到这一点?
unsigned char checksum(unsigned char message[], int nBytes)
{
unsigned char sum = 0;
while (nBytes-- > 0)
{
sum += *(message++);
}
return (~sum);
}
例如,当添加两个字节时,这就是我试图实现的那种环绕:
1001 1100
+1100 0010
------------
0101 1111 (sum)
1010 0000 Checksum (1's complement)
最佳答案
这是一个不寻常的要求,但这应该可以解决问题(没有提出效率要求):
unsigned char checksum(unsigned char message[], int nBytes)
{
unsigned char sum = 0;
while (nBytes-- > 0)
{
int carry = (sum + *message > 255) ? 1 : 0;
sum += *(message++) + carry;
}
return (~sum);
}
由于通常的算术转换,算术和比较是使用 int
完成的。
关于c - C 中带环绕的 8 位校验和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26478827/