7
Je l'extrait de code de code suivant en C++:impression des valeurs négatives que hexadécimal en python
for (int x = -4; x < 5; ++x)
printf("hex x %d 0x%08X\n", x, x);
et sa sortie 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 je tente la même chose en python:
for x in range(-4,5):
print "hex x", x, hex(x)
Je décrois ce qui suit:
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
Ou ceci:
for x in range(-4,5):
print "hex x %d 0x%08X" % (x,x)
Ce qui donne:
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
Ce n'est pas ce que je pensais. Y a-t-il un truc de formatage qui me manquera et qui tournera -4 en 0xFFFFFFFC au lieu de -0x04?
Pour inverser: h = int (s, 16); s, n = h >> 31, h & 0x7fffffff; return n sinon s (else -0x80000000 + n) –
Pour plus de 32 bits, utilisez 'hex (x + 16 ** number_of_hex_digits)'. Par exemple x = -9999999999 à 40 chiffres hexadécimaux devient '0xfffffffffffffffffffffffffffffffdabf41c01L' –