2012-11-21 21 views

risposta

6

Almeno bash supporta direttamente interi esadecimali, purché siano preceduti da 0x:

$ [[ 0xdead -lt 0xcafe ]] && echo yes || echo no 
no 
$ [[ 0xdead -gt 0xcafe ]] && echo yes || echo no 
yes 

Basta usare gli operatori di confronto normalmente ...

+0

hey ho ancora un dubbio: come verificare se l'input è numero o stringa? – bd1257

0

Come su

(("$answer" == 0x42)) 
echo $? 

answer=0xDEADCAFE 
(("$answer" == 0xDEADCAFE)) 
echo $? 
+0

che dire di a, b, c, d, e, f? – bd1257

+0

@ user1812956 Dovrebbe funzionare bene – cnicutar

0

In realtà @thkala answer funzionerà solo per numeri non maggiori di 0x7fffffffffffffff (LLONG_MAX):

$ [[ 0xa000000000000000 -lt 0x6000000000000000 ]] && echo -1                                              
-1 
$ [[ 0xa00000000000000 -lt 0x600000000000000 ]] && echo -1 || echo 1 
1 

Per i numeri più grandi, allora si potrebbe usare LLONG_MAXgdb, ma sarà più lento funziona naturalmente:

function cmp()                                
{                                   
    gdb -ex "p ${1}ULL == ${2}ULL ? 0 : (${1}ULL < ${2}ULL ? -1 : 1)" -batch |& grep '^$1' | cut -d' ' -f3                                          
} 

$ cmp 0xa000000000000000 0x6000000000000000 
1 
$ cmp 0xa00000000000000 0x600000000000000 
1 
+0

In realtà @thkala answer funzionerà solo per numeri non maggiori di 0x7fffffffffffffff (LLONG_MAX). Per i numeri maggiori di LLONG_MAX potresti usare gdb, ma ovviamente funzionerà più lentamente. (guarda come questa informazione, non direttamente in risposta alla domanda, rientra in un ** commento **.) (ancora 300 caratteri a sinistra) –

Problemi correlati