Printing negative values as hex in python

醉酒当歌 提交于 2019-12-19 17:42:15

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/3831833/printing-negative-values-as-hex-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!