python3:如何获取二进制数的逻辑补码(取反),例如'010'=> '101'? [英] python3: How to get logical complement (negation) of a binary number, eg. '010' => '101'?

查看:659
本文介绍了python3:如何获取二进制数的逻辑补码(取反),例如'010'=> '101'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我缺少了一些东西,但是我找不到一种简单的方法来完成这个简单的任务.当我通过〜"运算符取反二进制数时,由于两者的补码,它会返回负数:

Maybe I'm missing something but I can't find a straightforward way to accomplish this simple task. When I go to negate a binary number through the "~" operator it returns a negative number due to the two's complement:

>>> bin(~0b100010) # this won't return '0b011101'
'-0b100011'

如果我只想像传统的逻辑补码那样将0转换为1,反之亦然呢?

What about if I just want to switch 0s into 1s and vice-versa, like in classic logical complement?

推荐答案

>>> bin(0b111111 ^ 0b100010)
'0b11101'
>>> 

这篇关于python3:如何获取二进制数的逻辑补码(取反),例如'010'=> '101'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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