Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are hexadecimal numbers automatically converted to decimal?

I am working on a little Python method that needs to read a dictionary from another file that will represent the key and values.

But it seems I am running into a problem with the representation of the number values that I am sending over. For example, some keys in my dictionary would look like this:

id_dict = {
    'val_a': 0x0000,
    'val_b': 0x1000
}

But I noticed that when I attempt to iterate through the dictionary, the hexadecimal is replaced with the decimal value. Even in the original id_dict.py, where the dictionary is located, the numbers are converted from hex automatically.

This is my result of trying to iterate through it:

for k,v in id_dict.items():
    print(k,v)

#Results
val_a 0
val_b 4096

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?

And if there is a way to stop the automatic conversion, that would be great to understand as well!

like image 275
Ryan O Avatar asked Dec 19 '22 15:12

Ryan O


2 Answers

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:

>>> print 0x1000
4096
>>> print hex(0x1000)
0x1000
like image 182
user2357112 supports Monica Avatar answered Dec 21 '22 05:12

user2357112 supports Monica


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 in zip('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
like image 24
juanpa.arrivillaga Avatar answered Dec 21 '22 05:12

juanpa.arrivillaga