负数与正数之间按位与(&)? [英] Bitwise AND (&) between negative and positive numbers?
问题描述
我一直在学习如何使用位操作将两个数相加,但是在理解如何用Python处理负数时遇到了一些问题.例如,如果我尝试&
以下内容:
I've been learning about adding two numbers using bit manipulation and I am having issues understanding how it is done in Python for negative numbers. For example, if I am trying to &
the following:
-0b1111010 (-122) & 0b11011110 (222)
应该不是:
0b1111010
& 0b11011110
------------
0b01011010
因为只有1的结果与1的组合?
since only a combination of 1's results in 1's?
现在python给出0b10000110
Right now python gives 0b10000110
特别是当使用python将负数添加到正数时,我找不到任何资源.
I couldn't find any resources specifically when a negative number is added to a positive number using python.
推荐答案
这是因为Python使用二进制补码二进制有符号整数表示形式.这是一段代码,其输出显示实际的字节数据并说明 为什么 ,您将得到的结果是
It's because Python uses a two's complement binary signed integer representation. Here a snippet of code whose output shows the actual byte data and illustrates why you're getting the results that you are:
import math
def bin_format(integer):
num_bytes = math.ceil(integer.bit_length()/8) # Number required to represent value.
ba = integer.to_bytes(num_bytes, 'big', signed=integer<0)
return ''.join('{:08b}'.format(b) for b in ba) + ' ({:4d})'.format(integer)
print(' ' + bin_format(-122))
print('& ' + bin_format(222))
print('=' * 17)
print(' ' + bin_format(-122 & 222))
输出:
10000110 (-122)
& 11011110 ( 222)
=================
10000110 ( 134)
这篇关于负数与正数之间按位与(&)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!