5

python实现负数补码

 2 years ago
source link: http://blog.wen2go.site/2022/01/19/python%E5%AE%9E%E7%8E%B0%E8%B4%9F%E6%95%B0%E8%A1%A5%E7%A0%81/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Python有一个和其他语言完全不一样的地方,就是对负数的二进制表示。Python里的数是无所谓Overflow的,即没有位数限制,因此也就无所谓补码,因为补码都是相对于位数来说的,32位补码和16位补码,肯定是不一样的。但是这样就导致了一个问题,就是无法直接得到32位二进制补码。

  • 原数值获取补码

    def intToBin32(i):
    return (bin(((1 << 32) - 1) & i)[2:]).zfill(32)
  • 补码转成原数值

    def bin32ToInt(s):
    return int(s[1:], 2) - int(s[0]) * (1 << 31)

同理,求出二进制补码就可以根据二进制算出对应的16进制补码,8进制补码

int(value, 2)  # 将2进制转为10进制
int(value, 8) # 将8进制转为10进制
int(value, 16) # 将16进制转为10进制
hex(value) # 10进制转16进制
ord(value) # 8进制转16进制
bin(value) # 2进制转16进制

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK