如何在Python中解析十六进制或十进制int [复制]

时间:2022-10-30 15:03:36

This question already has an answer here:

这个问题在这里已有答案:

I have a string that can be a hex number prefixed with "0x" or a decimal number without a special prefix except for possibly a minus sign. "0x123" is in base 16 and "-298" is in base 10.

我有一个字符串,可以是前缀为“0x”的十六进制数字或没有特殊前缀的十进制数字,除了可能的减号。 “0x123”在基数16中,“ - 298”在基数10中。

How do I convert this to an int or long in Python?

如何在Python中将其转换为int或long?

I don't want to use eval() since it's unsafe and overkill.

我不想使用eval(),因为它不安全和过度杀伤。

5 个解决方案

#1


52  

int("0x123", 0)

(why doesn't int("0x123") do that?)

(为什么int(“0x123”)不这样做?)

#2


26  

Base 16 to 10 (return an integer):

基数16到10(返回一个整数):

>>> int('0x123', 16)
291

Base 10 to 16 (return a string):

基数10到16(返回一个字符串):

>>> hex(291)
'0x123'

#3


5  

Something like this might be what you're looking for.

这样的事情可能就是你想要的。

def convert( aString ):
    if aString.startswith("0x") or aString.startswith("0X"):
        return int(aString,16)
    elif aString.startswith("0"):
        return int(aString,8)
    else:
        return int(aString)

#4


0  

If you are doing a lot of go between with different number systems, the bitstring library make a lot of binary/Hex operations easier. It also supports string interpretation:

如果你在不同的数字系统之间做了很多工作,那么bitstring库使得很多二进制/ Hex操作更容易。它还支持字符串解释:

http://pythonhosted.org/bitstring/

http://pythonhosted.org/bitstring/

#5


-2  

This is a simpler version which works like a charm. Returns string since hex() returns the same type:

这是一个更简单的版本,就像一个魅力。返回字符串,因为hex()返回相同的类型:

def itoh(int): return hex(int)[2:]

#1


52  

int("0x123", 0)

(why doesn't int("0x123") do that?)

(为什么int(“0x123”)不这样做?)

#2


26  

Base 16 to 10 (return an integer):

基数16到10(返回一个整数):

>>> int('0x123', 16)
291

Base 10 to 16 (return a string):

基数10到16(返回一个字符串):

>>> hex(291)
'0x123'

#3


5  

Something like this might be what you're looking for.

这样的事情可能就是你想要的。

def convert( aString ):
    if aString.startswith("0x") or aString.startswith("0X"):
        return int(aString,16)
    elif aString.startswith("0"):
        return int(aString,8)
    else:
        return int(aString)

#4


0  

If you are doing a lot of go between with different number systems, the bitstring library make a lot of binary/Hex operations easier. It also supports string interpretation:

如果你在不同的数字系统之间做了很多工作,那么bitstring库使得很多二进制/ Hex操作更容易。它还支持字符串解释:

http://pythonhosted.org/bitstring/

http://pythonhosted.org/bitstring/

#5


-2  

This is a simpler version which works like a charm. Returns string since hex() returns the same type:

这是一个更简单的版本,就像一个魅力。返回字符串,因为hex()返回相同的类型:

def itoh(int): return hex(int)[2:]