How to compare hexadecimal numbers with hexadecimal numbers in a shell?

How to compare a hexadecimal number with hexadecimal numbers in a shell?

+7
source share
3 answers

At least bash supports hexadecimal integers if they are prefixed with 0x :

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

You just use comparison operators ...

+6
source

What about

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

In fact, @thkala's answer will only work for numbers no more than 0x7fffffffffffffff ( LLONG_MAX ):

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

For numbers larger than LLONG_MAX you can use gdb , but it will work slower, of course:

 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
source

All Articles