如何在没有转换

时间:2017-05-22 14:00:53

标签: python hex

我想将十六进制字符串转换为int但没有更改值。

例如

>>> int_value = 0xb19bc74cf4 
>>> print type(int_value)
<type 'int'>

现在我有一个字符串

>>> str_value = "0xb19bc74cf4"
>>> print type(str_value)
<type 'str'>

我现在如何将str_value转换为int_value?

期望的价值结果将是:

input: str_value = "0xb19bc74cf4"
Output: int_value = 0xb19bc74cf4
Print of int_value to be 0xb19bc74cf4
print of type(int_value) to be <type 'int'>

1 个答案:

答案 0 :(得分:0)

您需要意识到int内部是二进制值。没有办法“保留为十六进制值,但作为int类型”。 print将其转换回字符串进行展示,您可以使用format自定义转化:

>>> str_value = '0xb19bc74cf4'
>>> str_value
'0xb19bc74cf4'
>>> n = int(str_value,16)
>>> print(n) # default is to print in base 10
762822741236
>>> print(format(n,'#x')) # format in base 16 with "0x" prepended.
0xb19bc74cf4