Why Are Hexadecimal Numbers Automatically Converted To Decimal?
Solution 1:
Can someone tell me why the values are being represented in decimal form and not in the hexadecimal form that they are originally stored in?
They were not originally stored in hexadecimal. Python does not track any information about base; whether you type 0x1000
or 4096
in your source code, it's the same number, and Python stores it the same way.
When Python prints a number, it has to choose a base to display it in, and the default is always decimal. If you want to print it differently, you will need to specify a different way to perform string conversion, such as the hex
function:
>>>print0x1000
4096
>>>printhex(0x1000)
0x1000
Solution 2:
Python stores the numbers the same way, the only thing that changes is the formatting. Your issue is how the numbers are being formatted, not represented, thus, you fix your problem with string formatting:
>>> d = {k:v for k,v inzip('abcdefg',range(1,5000,313))}
>>> d
{'e': 1253, 'g': 1879, 'a': 1, 'd': 940, 'c': 627, 'b': 314, 'f': 1566}
>>> for k,v in d.items():
... print("{} {:#06x}".format(k,v))
...
e 0x04e5
g 0x0757
a 0x0001
d 0x03ac
c 0x0273
b 0x013a
f 0x061e
Post a Comment for "Why Are Hexadecimal Numbers Automatically Converted To Decimal?"