How to compare hexadecimal number with hexadecimal numbers in shell?
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).
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.
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.
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...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With