2012-12-22 8 views
7

ingresso = 'FFFF' # 4 ASCIICome posso convertire una stringa esadecimale ASCII in un numero intero con segno

risultato desiderato di F ... -1 come un intero

codice

cercato:

hexstring = 'FFFF' 
result = (int(hexstring,16)) 
print result #65535 

Risultato: 65535

Nulla di ciò che ho provato sembra aver riconosciuto che un 'FFFF' è una rappresentazione di un numero negativo.

+1

qualcosa come (non conosco la sintassi) 'if (valore> 0x7FFF) valore - = 0x10000'? –

risposta

10

Python converte FFFF al 'valore nominale', a decimale 65535

input = 'FFFF' 
val = int(input,16) # is 65535 

Lo vuoi interpretato come un numero con segno a 16 bit. Il seguente codice avrà i 16 bit inferiori di qualsiasi numero e 'registrati estendere', cioè interpretare come valore con segno a 16 bit e fornire il numero intero corrispondente

val16 = ((val+0x8000)&0xFFFF) - 0x8000 

Ciò è facilmente generalizzabile

def sxtn(x, bits): 
    h= 1<<(bits-1) 
    m = (1<<bits)-1 
    return ((x+h) & m)-h 
+0

E sì, 'se val> = 0x8000: val - = 0x10000' funziona bene anche nel caso in cui l'input sia noto come 0 .. 0xFFFF (da Jan Dvorak). – greggo

2

In un linguaggio come C, 'FFFF' può essere interpretato come un valore firmato (-1) o senza segno (65535). Puoi usare il modulo struct di Python per forzare l'interpretazione che vuoi.

Si noti che potrebbero esserci problemi di endianness che il codice di seguito non tenta di gestire e che non gestisce i dati lunghi più di 16 bit, quindi è necessario adattarsi se uno di questi casi è in effetti per te.

import struct 

input = 'FFFF' 

# first, convert to an integer. Python's going to treat it as an unsigned value. 
unsignedVal = int(input, 16) 
assert(65535 == unsignedVal) 
# pack that value into a format that the struct module can work with, as an 
# unsigned short integer 
packed = struct.pack('H', unsignedVal) 
assert('\xff\xff' == packed) 

# ..then UNpack it as a signed short integer 
signedVal = struct.unpack('h', packed)[0] 
assert(-1 == signedVal) 
+0

L'endianness non è un problema qui, poiché le operazioni h e H avranno sempre la stessa endianness. – greggo

+0

Ah, vero. +1 alla tua risposta. – bgporter