C中带环绕的8位校验和



我做了一个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);
}

由于通常的算术转换,使用CCD_ 1进行算术和比较。

最新更新