[英]8 bit checksum with wraparound in C
我已經做了一個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
進行算術和比較。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.