Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1875449
  • 博文数量: 376
  • 博客积分: 2147
  • 博客等级: 大尉
  • 技术积分: 3642
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-06 10:47
文章分类

全部博文(376)

文章存档

2019年(3)

2017年(28)

2016年(15)

2015年(17)

2014年(182)

2013年(16)

2012年(115)

我的朋友

分类: 嵌入式

2014-01-14 10:48:17

用几个数试了一下,16bit字折半相加就是模2^16-1,然后再取反,跟先取反再求和的结果是一样的,又想到以前看到
过1的补码,2的补码,到网上搜了下找到这个:

It is the 1’s complement of the 1’s complement sum of all the 16-bit words in the TCP header and data       这是关于TCP头部校验和字段(checksum field)的说明。
补码:补码是计算机中二进制数表达负数的办法,这样可以在计算机中把两个数的减法变成加法。补码形式有1的补码和2的补码,其中1的补码用在IPTCP的校验和中;
The checksum algorithm is simply to add up all the 16-bit words in one's complement and then to take the one's complement of the sum.
1's Complement Arithmetic
The Formula
~N = (2^n -1) - N
where: n is the number of bits per word
N is a positive integer
~N is -N in 1's complement notation
For example with an 8-bit word and N = 6, we have:
~N = (2^8 -1) - 6 = 255 - 6 = 249 = 11111001

In Binary
An alternate way to find the 1's complement is to simply
take the bit by bit complement of the binary number.
For example: N = +6 = 00000110
N = -6 = 11111001
Conversely, given the 1's complement we can find the
magnitude of the number by taking it's 1's complement.
The largest number that can be represented in 8-bit 1's
complement is 01111111 = 127 = 0x7F. The smallest is
10000000 = -127. Note that the values 00000000 and
11111111 both represent zero.
Addition
End-around Carry. When the addition of two values
results in a carry, the carry bit is added to the sum in the
rightmost position. There is no overflow as long as the
magnitude of the result is not greater than 2^n-1.
2's Complement Arithmetic
The Formula
N* = 2^n - N
where: n is the number of bits per word
N is a positive integer
N* is -N in 2's complement notation
For example with an 8-bit word and N = 6, we have:
N* = 2^8 - 6 = 256 - 6 = 250 = 11111010

In Binary
An alternate way to find the 2's complement is to start at
the right and complement each bit to the left of the first
"1".
For example: N = +6 = 00000110
N* = -6 = 11111010
Conversely, given the 2's complement we can find the
magnitude of the number by taking it's 2's complement.
The largest number that can be represented in 8-bit 2s
complement is 01111111 = 127. The smallest is
10000000 = -128.
Addition
When the addition of two values results in a carry, the
carry bit is ignored. There is no overflow as long as the
is not greater than 2^n-1 nor less than -2^n.

看来这里的反码求和就是求所有16bit字的1的补码的和,再对和求1的补码,1的补码也就是反码,这样上面的程序就明白多了。
阅读(2986) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~