如何在python中将有符号整数转换为无符号整数 [英] How to convert signed to unsigned integer in python

查看:144
本文介绍了如何在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.

推荐答案

假设:

  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 (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中将有符号整数转换为无符号整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆