md 格式
补码的定义
正数的补码与它的原码(Sign-Magnitude Form)相同。
负数的补码则是通过将对应正数的原码取反(即每一位取反,包括符号位),再加1 得到。
不过我知道一种方法可以快速的算出负数的补码,这种方式是通过负数的原码来计算的。因为负数的原码和正数的原码就一个符号位不相同,所以在取反的过程中,符号位可以看做是提前取反了,所以符号位不变。然后再由于最后需要加上一个1,这样的话,不管位数进位还是不进位,我们是先取反再加+1,连在一起的0,总是不变的,因为取反之后,+1的话,那么全部都变成0了,最后改变的时连在一起的0前面的1,这个1取反之后变成0,然后+1变成1,也是不变的,不过到此为止,在这个1前面的所有数字都是取反了的。那么根据定义这个规律,可以总结出一种由负数原码求补码的简单方法:从右向左,找到第一个1,这个1前面的所有位置,除了符号位之外,全部取反。这样就根据补码的定义,得出了一个由负数原码求负数补码的过程。
Definition of Two's Complement
The two's complement of a positive number is the same as its sign-magnitude form.
For negative numbers, the two's complement is obtained by inverting all the bits of the corresponding positive number (i.e., flipping every bit, including the sign bit) and then adding 1.
However, I know a quick way to calculate the two's complement of a negative number directly from its sign-magnitude representation. Since the only difference between the sign-magnitude forms of a positive and negative number is the sign bit, during the inversion process, the sign bit can be considered already inverted, so it remains unchanged. Additionally, due to the final step of adding 1, regardless of whether there's a carry or not, the sequence of trailing zeros remains unchanged. This is because after inversion, adding 1 will turn all the zeros into zeros again. The only change happens to the first 1 before the sequence of zeros—this 1 is inverted to 0, and then adding 1 makes it 1 again, so it stays the same. Up to this point, all the bits before this 1 have been inverted. Thus, based on this rule, we can summarize a simple method to compute the two's complement from the sign-magnitude representation of a negative number: Starting from the rightmost bit, find the first 1. All the bits before this 1, except for the sign bit, should be inverted. In this way, you derive the two's complement of a negative number directly from its sign-magnitude form.
Top comments (0)