Stampa valori negativi come esadecimale in pitone
-
26-09-2019 - |
Domanda
ho il seguente frammento di codice in C ++:
for (int x = -4; x < 5; ++x)
printf("hex x %d 0x%08X\n", x, x);
E la sua uscita è
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
Se provo la stessa cosa in python:
for x in range(-4,5):
print "hex x", x, hex(x)
ottengo il seguente
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
O questo:
for x in range(-4,5):
print "hex x %d 0x%08X" % (x,x)
Il che dà:
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
Questo non è quello che mi aspettavo. C'è qualche trucco formattazione che mi manca che si trasformerà in -4 0xfffffffc invece di -0x04?
Soluzione
È necessario limitare in modo esplicito il numero intero a 32 bit:
for x in range(-4,5):
print "hex x %d 0x%08X" % (x, x & 0xffffffff)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow