gpt4 book ai didi

binary - -128 和 128 在 2 的补码中

转载 作者:行者123 更新时间:2023-12-04 03:08:17 26 4
gpt4 key购买 nike

在 2 的补码中,0-127 表示为 00000000 到 01111111。在负数的情况下,我们将无符号表示中的所有位取反并加 1 以获得 2 的补码。

(引用:http://en.wikipedia.org/wiki/Signed_number_representations#Two.27s_complement)

所以 2 的补码中的 -1 将是:

无符号 1 = 00000001

反转所有位 = 11111110

加 1 = 11111111

但是对于-128,如果我们按照相同的步骤:

无符号 128 = 10000000

反转所有位= 01111111

加 1 = 10000000

所以 -128 和 128 在 2 的补码表示法中具有相同的表示?为什么 8 位的 2 的补码范围不是 -127 到 128?简而言之,为什么 -128 比使用相同位数表示无符号 128 更受欢迎?

最佳答案

有符号字节中没有“128”。范围是

  • 0 到 127:128 个值
  • -1 到 -128:128 个值

  • 总共 256 个值,即 2^8。
    基于评论的附录(并重新阅读问题) 0x80可能被认为是 -128 或 +128。 Wikipedia explanation值得一读

    The two's complement of the minimum number in the range will not have the desired effect of negating the number.

    For example, the two's complement of −128 in an 8-bit system results in the same binary number. This is because a positive value of 128 cannot be represented with an 8-bit signed binary numeral. Note that this is detected as an overflow condition since there was a carry into but not out of the most-significant bit. This can lead to unexpected bugs in that an unchecked implementation of absolute value could return a negative number in the case of the minimum negative. The abs family of integer functions in C typically has this behaviour. This is also true for Java. In this case it is for the developer to decide if there will be a check for the minimum negative value before the call of the function.

    The most negative number in two's complement is sometimes called "the weird number," because it is the only exception. Although the number is an exception, it is a valid number in regular two's complement systems. All arithmetic operations work with it both as an operand and (unless there was an overflow) a result.


    此外,右移有符号整数将使 CPU 向右传播 MSb(位 7),如果 0x80,这将违反简单逻辑。是 +128,因为只经过一个类次,我们就会得到 0xC0这是一个负数 (-64)...(而从正数右移通常不会产生负结果)。

    关于binary - -128 和 128 在 2 的补码中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17007627/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com