如何在python中将signed转换为无符号整数 [英] How to convert signed to unsigned integer in python
问题描述
假设我有这个号码 i = -6884376
。
如何将其称为无符号变量?
类似(无符号长)i
在C中。
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.
推荐答案
假设:
- 您考虑到了2的补码表示;并且,
- 按
(unsigned long)
你意味着无符号32位整数,
- You have 2's-complement representations in mind; and,
- 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.
这篇关于如何在python中将signed转换为无符号整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!