7
tengo el siguiente fragmento de código en C++:valores negativos de impresión como hexagonal en Python
for (int x = -4; x < 5; ++x)
printf("hex x %d 0x%08X\n", x, x);
y su salida está
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
Si intento lo mismo en Python:
for x in range(-4,5):
print "hex x", x, hex(x)
obtengo el siguiente
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 esto:
for x in range(-4,5):
print "hex x %d 0x%08X" % (x,x)
cual da:
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
Esto no es lo que esperaba. ¿Hay algún truco de formato que me falta que convertirá -4 en 0xFFFFFFFC en lugar de -0x04?
Para invertir: h = int (s, 16); s, n = h >> 31, h & 0x7fffffff; return n if not s else (-0x80000000 + n) –
Para más de 32 bits, use 'hex (x + 16 ** number_of_hex_digits)'. Por ejemplo, x = -9999999999 a 40 dígitos hexadecimales se convierte en '0xfffffffffffffffffffffffffffffffdabf41c01L' –