2010-09-30 11 views
7

Ich habe den folgenden Code-Schnipsel in C++:Druck negative Werte als Hex in Python

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

und sein Ausgang ist

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 

Wenn ich die gleiche Sache in Python versuchen:

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

Ich bekomme folgende

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 

Oder diese:

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

Welche gibt:

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 

Das ist nicht das, was ich erwartet hatte. Gibt es einen Formatierungstrick, der -4 zu 0xFFFFFFFC anstelle von -0x04 macht?

Antwort

15

Sie müssen explizit die ganze Zahl auf 32 Bit eingeschränkt:

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

zu Umkehren: h = int (s, 16); s, n = h >> 31, h & 0x7fffffff; return n wenn nicht s else (-0x80000000 + n) –

+1

Verwenden Sie für mehr als 32 Bits 'hex (x + 16 ** number_of_hex_digits)'. Zum Beispiel x = -9999999999 bei 40 Hex-Ziffern wird '0xfffffffffffffffffffffffffffffffffdabf41c01L' –