"Bitwise not" in Python not considering 2 additions

I need to perform the "~" operation in Python, but not considering 2 additions. I managed to do this using XOR , do you know another way to do this? (more efficient)

a = 0b101 b = 0b10101 print bin(a ^ (2 ** a.bit_length() - 1)) #0b10 print bin(b ^ (2 ** b.bit_length() - 1)) #0b1010 
+5
source share
2 answers

What ~ already doing. The hard part is that Python has unlimited integers of length, so when you invert a number, this sign is expanded with - at least conceptually - an infinite number 1. This means you get negative numbers.

 >>> bin(~0b101) '-0b110' >>> bin(~0b10101) '-0b10110' 

To convert them to unsigned numbers, you need to decide how many bits you need. Perhaps you are working with 8-bit bytes. Then you could And them with a 1-bit byte:

 >>> bin(~0b101 & 0xFF) '0b11111010' >>> bin(~0b10101 & 0xFF) '0b11101010' 

Or, if you want to combine the exact bit length of the input numbers, your decision is reasonable. For efficiency, you can switch the exponent to shift left. And it may be more understandable to use ~ and & instead of ^ .

 >>> bin(~a & ((1 << a.bit_length()) - 1)) '0b10' >>> bin(~b & ((1 << b.bit_length()) - 1)) '0b1010' 

(I suspect that a hard encoding such as & 0xFFFF would be the right decision in practice. I cannot come up with a good real case of using bit_length() in the world for the answer.)

+4
source

Another way, although some (including me) may dispute it better:

 from string import maketrans tbl = maketrans("01","10") int(bin(42)[2:].translate(tbl),2) 

The first bit simply sets the translation table to invert bits 1 and 0 in the string.

The second bit receives the binary representation ( 420b101010 ), discards 0b in front and inverts the bits through translation. Then you just use int(,2) to turn this binary string back into a number.


If you can limit it to a specific width, rather than using the width of the number itself, then this is a simple matter (using an example of 32 bits):

 val = val ^ 0xffff 
0
source

Source: https://habr.com/ru/post/1202204/


All Articles