且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在python中将signed转换为无符号整数

更新时间:2022-12-15 11:01:40

假设


  1. 您考虑到了2的补码表示;并且,

  2. (unsigned long)意味着无符号32位整数,

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

然后你只需要添加 2 ** 32(或1<< 32)到负值。

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

例如,将此应用于-1:

For example, apply this to -1:

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

假设#1表示你希望-1成为被视为1位的实心字符串,假设#2意味着你想要32位。

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.

但是你可以说出你的隐藏假设是什么。例如,如果您考虑到1的补码表示,那么您需要应用前缀运算符。 Python整数努力工作以给出使用无限宽2的补码表示的假象(如常规2的补码,但具有无限数量的符号位)。

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").

和要复制平台C编译器的功能,可以使用 ctypes 模块:

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 unsigned long 恰好是运行此示例的框上的4个字节。

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