How to convert signed to unsigned integer in python(如何在python中将有符号整数转换为无符号整数)
问题描述
假设我有这个号码 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.
推荐答案
假设:
- 您想到了 2 的补码表示;并且,
- 按
(unsigned long)你意思是无符号 32 位整数,
- You have 2's-complement representations in mind; and,
- By
(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中将有符号整数转换为无符号整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在python中将有符号整数转换为无符号整数
基础教程推荐
- Discord.py 缺少必需的参数 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
