59

I want to convert a hex string (ex: 0xAD4) to hex number, then to add 0x200 to that number and again want to print that number in form of 0x as a string.

i tried for the first step:

str(int(str(item[1][:-2]),16))

but the value that is getting printed is a decimal string not a hex formatted string (in 0x format) ( i want to print the final result in form of 0x)

  • [:-2] to remove the last 00 from that number
  • item[1] is containing hex number in form of 0x
RATHI
  • 5,129
  • 8
  • 39
  • 48
  • 9
    There's no such thing in Python as a hex number. There's just numbers. So you want to convert a hex string to a number, not to a hex number, then you want to print a number as hex. – Steve Jessop Feb 19 '14 at 11:45
  • 1
    @SteveJessop your comment is answer, and both answer are comment :) – Grijesh Chauhan Feb 19 '14 at 11:47
  • 1
    @GrijeshChauhan: no, it's not an answer. The question contains a misconception, but after correcting that misconception the question still stands and my comment doesn't answer it. The answers do. – Steve Jessop Feb 19 '14 at 11:48
  • 1
    @SteveJessop yes but I think the important point that should be explained in answer that hex is just representation all numbers stores in same ways(that you says) And hence there is no difference between `2772` and `0XAD4`. So if `i = 0XAD4` then `print i` will outputs `2772` but not `ad4` OP need to use `%x`. – Grijesh Chauhan Feb 19 '14 at 11:52
  • Possible duplicate of [Convert hex string to int in Python](https://stackoverflow.com/q/209513/608639) – jww Dec 25 '18 at 15:18

3 Answers3

117

Try this:

hex_str = "0xAD4"
hex_int = int(hex_str, 16)
new_int = hex_int + 0x200
print hex(new_int)

If you don't like the 0x in the beginning, replace the last line with

print hex(new_int)[2:]
Bach
  • 6,145
  • 7
  • 36
  • 61
  • 4
    I like to be more explicit: `int(hex_str, base=16)` rather than `int(hex_str, 16)`. Note that the documentation for `int()` is here: https://docs.python.org/3/library/functions.html#int – Gabriel Staples Jun 22 '19 at 01:51
20

Use int function with second parameter 16, to convert a hex string to an integer. Finally, use hex function to convert it back to a hexadecimal number.

print hex(int("0xAD4", 16) + int("0x200", 16)) # 0xcd4

Instead you could directly do

print hex(int("0xAD4", 16) + 0x200) # 0xcd4
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • 1
    I believe OP's confusing is that he differentiates between `i = 0xad4` and `i = 2772` when he prints `i`. (and seems when I reads his thanks) Anyways + to both of you as I didn't now `hex( )` – Grijesh Chauhan Feb 19 '14 at 11:56
0

Use format string

intNum = 123
print "0x%x"%(intNum)

or hex function.

intNum = 123
print hex(intNum)
Kei Minagawa
  • 4,395
  • 3
  • 25
  • 43