简体   繁体   中英

Declaring a variable as hex in Python

I have a variable

s=64

This variable is in hex. But Python takes it as decimal. 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?

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):

>>> s=0x64
>>> s
100
>>> hex(s)
'0x64'
>>> h = int(str(0x64), 16)
>>> h
256

Python stores an integer as a decimal (by default). 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.

The number 64 in hex (base 16) is 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:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM