6

I dont know why Hex function returns a string like '0x41' instead 0x41

enter image description here

I need to convert an ASCII value into a hex. But i want in 0x INT format, not into a '0x' string.

ascii = 360
hexstring = hex(ascii)
hexstring += 0x41  # i cant do this because hexstring is a string not a int hex

How i can get a int hex?? thanks

1
  • You are confusing the VALUE of an object with the REPRESENTATION of the object. A number does not have a representation. It is a binary value stored in memory. Whether you view that value as 'A' or 65 or 0x41 or 0o101 is just for human convenience. ALL of those things have the exact same internal value, and the human representation is going to be a string. Commented Apr 5 at 17:53

1 Answer 1

12

There is no int hex object. There is only an alternative syntax to create integers:

>>> 0x41
65

You could have used 0o101 too, to get the same value. Or use 0b1000001 to specify it in binary; they are all the exact same numeric value to Python; they are all just different forms to specify an integer value in your code.

Simply keep ascii as an integer and sum your hex notation values with that:

>>> ascii = 360
>>> ascii += 0x41
>>> ascii
425

hex() produces a string that can be interpreted by a Python program in the same manner, and is usually used when debugging code or quick presentation output (but you should use format(number, 'x') if you want to produce end-user output without the 0x prefix). It is not needed to work with integers.

Sign up to request clarification or add additional context in comments.

2 Comments

0o1010 in octal is 520, you misspelled an extra 0, the correct is 0o101=65, the same as the hex and the binary given. Site doesn't allow me to edit just one character.
@Santropedro: ugh, yes, you are right. No idea where that extra 0 came from, that's lost in the sands of time by now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.