有几种方法可以用二进制表示有符号数。您正在考虑sign-and-magnitude,这是 IEEE 浮点格式使用的。如您所述,单精度float
或双精度的最高有效位double
用于表示符号。现代计算机中的整数值以二进制补码表示。二进制补码中可表示的值的范围取决于使用了多少位。使用的位数取决于您的编译器、您正在编译的目标以及您选择的变量类型。一个 8 位二进制补码数可以表示 -128 到 +127 范围内的数字。在C
您通常会将该char
类型用于有符号的 8 位值,并且int
for a signed 32-bit value, all processors I'm aware of today would represent these in two's complement. To find out how many bytes of storage your system uses to store an int
you can use the sizeof
operator in C
, in most systems an int
is 4 bytes, or 32-bits. In an N-bit two's complement number the most significant bit (bit N-1) can, in fact, be used to determine the sign of the number, but the remaining bits are not to be interpreted as the magnitude.
See Wikipedia's article on two's complement.
One interesting fact of two's complement is that the most negative number representable in N bits has no representable positive counterpart in N bits. In other words, you cannot represent the absolute value of the most negative value. The most negative value in two's complement representable in N bits has the most significant bit (bit N-1) set, and the remaining bits 0, its value is -pow(2,N-1). For N=8 the most negative value is 0x80 and the value is -pow(2,8-1) which is -pow(2,7) or -128. The largest positive number representable in two's complement in 8 bits is 0x7F, a '0' in the most significant bit and '1' in the remaining bits, or pow(2,7)-1 or +127.