1

我有一个 64 位十六进制数,我想将其转换为无符号整数。我跑

>>> a = "ffffffff723b8640"
>>> int(a,16)
18446744071331087936L

那么数字末尾的“L”是什么?

使用以下命令也无济于事

>>> int(a,16)[:-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'long' object is unsubscriptable
>>> int(a,16).rstrip("L")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'long' object has no attribute 'rstrip'
4

3 回答 3

4

Python2.x has 2 classes of integer (neither of them are unsigned btw). There is the usual class int which is based on your system's concept of an integer (often a 4-byte integer). There's also the arbitrary "precision" type of integer long. They behave the same in almost1 all circumstances and int objects automatically convert to long if they overflow. Don't worry about the L in the representation -- It just means your integer is too big for int (there was an Overflow) so python automatically created a long instead.

It is also worth pointing out that in python3.x, they removed python2.x's int in favor of always using long. Since they're now always using long, they renamed it to int as that name is much more common in code. PEP-237 gives more rational behind this decision.

1The only time they behave differently that I can think of is that long's __repr__ adds that extra L on the end that you're seeing.

于 2013-05-29T17:47:43.493 回答
3

You are trying to apply string methods to an integer. But the string representation of a long integer doesn't have the L at the end:

In [1]: a = "ffffffff723b8640"

In [2]: int(a, 16)
Out[2]: 18446744071331087936L

In [3]: str(int(a, 16))
Out[3]: '18446744071331087936'

The __repr__ does, though (as @mgilson notes):

In [4]: repr(int(a, 16))
Out[4]: '18446744071331087936L'

In [5]: repr(int(a, 16))[:-1]
Out[5]: '18446744071331087936'
于 2013-05-29T17:47:54.703 回答
1

you can't call rstrip on an integer, you have to call it on the string representation of the integer.

>>> a = "ffffffff723b8640"
>>> b = int(a,16)
>>> c = repr(b).rstrip("L")
>>> c
'18446744071331087936'

Note however, that this would only be for displaying the number or something. Turning the string back into an integer will append the 'L' again:

>>> int(c)
18446744071331087936L
于 2013-05-29T17:48:01.557 回答