[英]Declaring a variable as hex in Python
I have a variable我有一个变量
s=64
This variable is in hex.这个变量是十六进制的。 But Python takes it as decimal.
但 Python 将其视为十进制。 How do I declare it as a hex variable?
如何将其声明为十六进制变量?
I know to declare something as hex, we use我知道将某些东西声明为十六进制,我们使用
s=0x64
But I have only但我只有
s=64
How can I go about this?我怎么能 go 关于这个?
I think that is something missing in your code theory or question.我认为这是您的代码理论或问题中缺少的东西。
One thing is the value and one another is presentation (interpretation) .一件事是价值,另一件事是呈现(解释) 。 So the value is 100 (decimal), but it can be seen ( converted ) as a decimal or hexadecimal (or whatever you like):
所以值为 100(十进制),但它可以被视为(转换)为十进制或十六进制(或任何你喜欢的):
>>> s=0x64
>>> s
100
>>> hex(s)
'0x64'
>>> h = int(str(0x64), 16)
>>> h
256
Python stores an integer as a decimal (by default). Python 将 integer 存储为十进制(默认情况下)。 If you want to have a number that acts as a hexadecimal you should code your own class and use the conversion routines I showed above.
如果你想要一个十六进制的数字,你应该编写自己的 class 并使用我上面显示的转换例程。
The number 64
in hex (base 16) is 100
.十六进制(以 16 为底)的数字
64
是100
。 To achieve you answer, you should use a combination of hex() , int() and str() If you start with s = 64
and you want to end up with s = 100
which is the decimal value of 0x64
, consider this code:为了得到你的答案,你应该使用hex() , int()和str()的组合如果你从
s = 64
开始,你想以s = 100
结束,这是0x64
的十进制值,考虑这个代码:
s = 64
s = int(str(s), 16)
If you want something else, please clarify what, and note that you can try to achieve it yourself with some combination of hex(), int() and str()如果您想要其他东西,请说明是什么,并注意您可以尝试使用 hex()、int() 和 str() 的某种组合来自己实现它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.