与1的补码二进制表示混淆 [英] Confusion with 1's compliment binary representation

查看:63
本文介绍了与1的补码二进制表示混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习负数的二进制表示形式.我尝试以二进制形式输出12和〜12.

I was trying to learn binary representation of negative numbers. I tried to output 12 and ~12 in binary.

print(~12)

输出:

-13

这是12的1的补码.

但是我怀疑二进制数 12是1100 ,而 -13(1的补码12)是0011 ,但是 3也是0011 二进制的.这对我来说很困惑.

But my doubt is that binary 12 is 1100 and -13 (1's complement of 12) is 0011 but 3 is also 0011 in binary. This was very confusing for me.

-13和3如何具有相同的二进制值?

How -13 and 3 can have same binary values?

推荐答案

TLDR:-13和3没有相同的二进制值.混淆源于忽略显式符号和填充/宽度.

TLDR: -13 and 3 do not have the same binary values. The confusion arises from ignoring explicit sign and padding/width.

Python整数表现为 unsigned 任意宽度的二进制数字,带有单独符号位.对于 signed 数字,没有通用,明确的二进制表示形式.

Python integers behave as unsigned arbitrary width binary numbers, with a separate sign bit. There is no general, unambiguous binary representation for signed numbers.

例如,12是数字 ... 1100 和符号 + ,而-12是相同的数字 ... 1100 ,但符号-.值得注意的是, ... 可以是任意许多前导数字,例如 1100 01100 001100 等.都是相同的数字.这种0填充可以像对待小数和大数一样处理.至少四位数的12 ... 1100 可以与至少五位数的16 ... 10000 对齐.

For example, 12 is the number ...1100 and the sign +, and -12 is the same number ...1100 but the sign -. Notably, the ... may be arbitrary many leading digits – 1100, 01100, 001100 and so on are all the same number. This 0-padding allows to treat small and large numbers alike, e.g. the at-least 4-digit 12 ...1100 can be aligned with the at-least 5-digit 16 ...10000.

这意味着不能有一个特定的前导符号位,因为每个位置之前都可以有另一个 0 .取而代之的是,符号位在数字的前面: 0 ... 1100 + ... 1100 是12,而 1 ... 1100 -... 1100 为-12.这在将符号和绝对值分开的数字的按位规范表示中可见.

This means there cannot be a specific leading sign bit, since each position could be preceded by another 0. Instead, the sign bit arbitrarily precedes the number: 0...1100 or +...1100 is 12, and 1...1100 or -...1100 is -12. This is visible in the canonical bitwise representation of numbers separating the sign and absolute value.

>>> bin(12)
0b1100
>>> bin(-12)
-0b1100

因此,4位按位补码12是 -0011 ,而3是 +0011 .

As such, the 4-digit bitwise complement of 12 is -0011, while 3 is +0011.

这篇关于与1的补码二进制表示混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆