Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare hexadecimal numbers with hexadecimal numbers in shell?

Tags:

bash

shell

How to compare hexadecimal number with hexadecimal numbers in shell?

like image 826
bd1257 Avatar asked Nov 21 '12 19:11

bd1257


People also ask

How do you evaluate hexadecimal?

Hexadecimal Number System Letters represents numbers starting from 10. A = 10, B = 11, C = 12, D = 13, E = 14, F = 15. Also called base 16 number system. Last position in a hexadecimal number represents an x power of the base (16).

How do you interpret hex values?

The first nine numbers (0 to 9) are the same ones commonly used in the decimal system. The next six two-digit numbers (10 to 15) are represented by the letters A through F. This is how the hex system uses the numbers from 0 to 9 and the capital letters A to F to represent the equivalent decimal number.

How do you tell if a number is negative or hexadecimal?

The hexadecimal value of a negative decimal number can be obtained starting from the binary value of that decimal number positive value. The binary value needs to be negated and then, to add 1. The result (converted to hex) represents the hex value of the respective negative decimal number.


2 Answers

At least bash supports hexadecimal integers directly, provided that they are prefixed with 0x:

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

You just use the comparison operators normally...

like image 55
thkala Avatar answered Oct 07 '22 01:10

thkala


You can convert your hex numbers into decimals using printf and then you can compare the numeric values, e.g.:

x="0xdead"
y="0xcafe"

x_num=$(printf "%d" "$x")
y_num=$(printf "%d" "$y")

if [ $x_num -gt $y_num ]; then
    echo "x is my value"
else
   echo "x is not my value"
fi
like image 30
neoben Avatar answered Oct 07 '22 02:10

neoben