9

I have the following code snippet in C++:

for (int x = -4; x < 5; ++x)
       printf("hex x %d 0x%08X\n", x, x);

And its output is

hex x -4 0xFFFFFFFC
hex x -3 0xFFFFFFFD
hex x -2 0xFFFFFFFE
hex x -1 0xFFFFFFFF
hex x 0 0x00000000
hex x 1 0x00000001
hex x 2 0x00000002
hex x 3 0x00000003
hex x 4 0x00000004

If I try the same thing in python:

for x in range(-4,5):
   print "hex x", x, hex(x)

I get the following

hex x -4 -0x4
hex x -3 -0x3
hex x -2 -0x2
hex x -1 -0x1
hex x 0 0x0
hex x 1 0x1
hex x 2 0x2
hex x 3 0x3
hex x 4 0x4

Or this:

for x in range(-4,5):
   print "hex x %d 0x%08X" % (x,x)

Which gives:

hex x -4 0x-0000004
hex x -3 0x-0000003
hex x -2 0x-0000002
hex x -1 0x-0000001
hex x 0 0x00000000
hex x 1 0x00000001
hex x 2 0x00000002
hex x 3 0x00000003
hex x 4 0x00000004

This is not what I expected. Is there some formatting trick I am missing that will turn -4 into 0xFFFFFFFC instead of -0x04?

grieve
  • 13,220
  • 10
  • 49
  • 61

1 Answers1

19

You need to explicitly restrict the integer to 32-bits:

for x in range(-4,5):
   print "hex x %d 0x%08X" % (x, x & 0xffffffff)
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • 1
    To invert: h = int(s, 16); s, n = h >> 31, h & 0x7fffffff; return n if not s else (-0x80000000 + n) – David Fraser May 20 '11 at 15:38
  • 1
    For more than 32 bits, use `hex(x + 16**number_of_hex_digits)`. For example x=-9999999999 at 40 hex digits becomes `0xfffffffffffffffffffffffffffffffdabf41c01L` – Bob Stein Mar 06 '15 at 14:29