从十六进制Python中的补 [英] From hexadecimal to one's complement in Python

查看:521
本文介绍了从十六进制Python中的补的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个简单的方法来产生蟒蛇一补?

Is there an easy way to produce a one's complement in python?

例如,如果你走的十六进制值 0x9E ,我需要将其转换为 0x61

For instance, if you take the hex value 0x9E, I need to convert it to 0x61.

我需要交换二进制1为0和0的对1的。这感觉就像这应该是简单的。

I need to swap the binary 1's for 0's and 0's for 1's. It feels like this should be simple.

推荐答案

只需使用的 XOR运算符 ^ 对0xFF的:

Just use the XOR operator ^ against 0xFF:

>>> hex(0x9E ^ 0xFF)
'0x61'

如果你需要大于一个字节值工作,您可以创建从面膜 int.bit_length()你的价值法

If you need to work with values larger than a byte, you could create the mask from the int.bit_length() method on your value:

>>> value = 0x9E
>>> mask = (1 << value.bit_length()) - 1
>>> hex(value ^ mask)
'0x61'
>>> value = 0x9E9E
>>> mask = (1 << value.bit_length()) - 1
>>> hex(value ^ mask)
'0x6161'

这篇关于从十六进制Python中的补的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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