1

First of all I'm not a Python expert, so here is my topic:

I want to invert a number, let say number = "ABCD123" (yes this is a string but I need to do it this way ...), the problem is that I'm not really satisfy with the way Python deal with the inversion, for example ~0xABCD123 is -180146468 and I don't want the MSB but only the "current" bits to be inverted. I can go with something like ~0xABCD123 & 0XFFFFFFF but the size of the number can actually change...

Question

Is there a way to dynamically "cast" or remove the bit sign in Python with the operator ~

Jaay
  • 2,103
  • 1
  • 16
  • 34
  • 1
    And if you want to do exactly what you have said, why not AND it with 16**(length of your string) - 1? – Atmaram Shetye Jun 24 '13 at 12:19
  • for example I have `0XD5` wich is binary `11010101`, when I do `~0xD5` the result is `-214` but I want the result to be the invert like `00101010`. Maybe I'm misunderstanding the concept of Python's `~` – Jaay Jun 24 '13 at 12:21
  • 2
    In that case, you are better off XORing with FF..F. I don't think there are unsigned integers in Python. – Atmaram Shetye Jun 24 '13 at 12:27
  • http://stackoverflow.com/questions/210629/python-unsigned-32-bit-bitwise-arithmetic. Possible duplicate! Check the 2nd answer with ctypes conversion... – Atmaram Shetye Jun 24 '13 at 12:29
  • I feel pretty stupid didn't think of XORing... it work well now :) thanks – Jaay Jun 24 '13 at 12:33

1 Answers1

4

A simple hack:

def invert_int(n):
    number_bit_len = n.bit_length()
    max_val = (2 ** number_bit_len) - 1
    return ~n & max_val
Samy Arous
  • 6,794
  • 13
  • 20
  • 1
    You can replace the first two lines with `n.bit_length()` which is also more reliable with big integers. Also using `2 ** number_bit_len - 1` would work for any integer size, while `math.pow` fails for big enough numbers. – Bakuriu Jun 24 '13 at 13:10
  • [`bit_length`](http://docs.python.org/dev/library/stdtypes.html#int.bit_length) is python 3 only – Eric Jun 24 '13 at 22:16
  • @lcfseth: Huh. The docs say _"New in version 3.1."_, but you're right, it works. – Eric Jun 25 '13 at 12:52