PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 9, 2022

[FIXED] Why are hexadecimal numbers automatically converted to decimal?

 August 09, 2022     decimal, dictionary, hex, python     No comments   

Issue

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!


Solution

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


Answered By - user2357112
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing