假设我有这个号码 i = -6884376.我如何将它称为无符号变量?类似于 C 中的 (unsigned long)i .
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.
假设:
(unsigned long) 你意思是无符号 32 位整数,(unsigned long) you mean unsigned 32-bit integer,那么你只需要将 2**32 (or 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中将有符号整数转换为无符号整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
python:不同包下同名的两个模块和类python: Two modules and classes with the same name under different packages(python:不同包下同名的两个模块和类)
配置 Python 以使用站点包的其他位置Configuring Python to use additional locations for site-packages(配置 Python 以使用站点包的其他位置)
如何在不重复导入顶级名称的情况下构造python包How to structure python packages without repeating top level name for import(如何在不重复导入顶级名称的情况下构造python包)
在 OpenShift 上安装 python 包Install python packages on OpenShift(在 OpenShift 上安装 python 包)
如何刷新 sys.path?How to refresh sys.path?(如何刷新 sys.path?)
分发带有已编译动态共享库的 Python 包Distribute a Python package with a compiled dynamic shared library(分发带有已编译动态共享库的 Python 包)