Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing negative values as hex in python

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?

like image 604
grieve Avatar asked Sep 30 '10 14:09

grieve


1 Answers

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)
like image 152
kennytm Avatar answered Sep 28 '22 08:09

kennytm