How to convert signed to unsigned integer in python

匿名 (未验证) 提交于 2019-12-03 02:44:02

问题:

Let's say I have this number i = -6884376. How do I refer to it as to an unsigned variable? Something like (unsigned long)i in C.

回答1:

Assuming:

  1. You have 2's-complement representations in mind; and,
  2. By (unsigned long) you mean unsigned 32-bit integer,

then you just need to add 2**32 (or 1 to the negative value.

For example, apply this to -1:

>>> -1 -1 >>> _ + 2**32 4294967295L >>> bin(_) '0b11111111111111111111111111111111' 

Assumption #1 means you want -1 to be viewed as a solid string of 1 bits, and assumption #2 means you want 32 of them.

Nobody but you can say what your hidden assumptions are, though. If, for example, you have 1's-complement representations in mind, then you need to apply the ~ prefix operator instead. Python integers work hard to give the illusion of using an infinitely wide 2's complement representation (like regular 2's complement, but with an infinite number of "sign bits").

And to duplicate what the platform C compiler does, you can use the ctypes module:

>>> import ctypes >>> ctypes.c_ulong(-1)  # stuff Python's -1 into a C unsigned long c_ulong(4294967295L) >>> _.value 4294967295L 

C's unsigned long happens to be 4 bytes on the box that ran this sample.



回答2:

To get the value equivalent to your C cast, just bitwise and with the appropriate mask. e.g. if unsigned long is 32 bit:

>>> i = -6884376 >>> i & 0xffffffff 4288082920 

or if it is 64 bit:

>>> i & 0xffffffffffffffff 18446744073702667240 

Do be aware though that although that gives you the value you would have in C, it is still a signed value, so any subsequent calculations may give a negative result and you'll have to continue to apply the mask to simulate a 32 or 64 bit calculation.



回答3:

Python doesn't have builtin unsigned types. You can use mathematical operations to compute a new int representing the value you would get in C, but there is no "unsigned value" of a Python int. The Python int is an abstraction of an integer value, not a direct access to a fixed-byte-size integer.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!