简体   繁体   English

在python中将负值打印为十六进制

[英]Printing negative values as hex in python

I have the following code snippet in C++: 我在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: 如果我在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? 是否有一些格式化技巧我将丢失,将-4转换为0xFFFFFFFC而不是-0x04?

You need to explicitly restrict the integer to 32-bits: 您需要将整数显式限制为32位:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM