Awk program: addhex
This Awk program will parse a file full of hexadecimal strings, converting the numbers to decimal, and giving a total.
- Hex numbers are can be prefixed with 0x, or $, or not prefixed at all.
- Example hex strings include $DeadBeef, 0x4E71, -ee7b, and 000069FF.
- Multiple numbers can be on each line.
- Other text is usually ignored properly.
- Numbers can be up to +/- 2^48, or 16^12, or $FFFFFFFFFFFF in size.
- The sum of the numbers must also be less than 2^48.
- Usage: addhex file
#!/usr/bin/env -S awk -f
# addhex - adds hex numbers.
# addhex is Copyright Daniel K. Allen, 2023-2025.
# All rights reserved.
#
# 12 Jul 2023 - Created by Dan Allen.
# 13 Jul 2023 - Uses hex2decimal(), and supports many numbers per line.
# 17 Sep 2025 - Supports negative numbers as well.
#
BEGIN {
sum = n = 0
a["0"] = 0; a["1"] = 1; a["2"] = 2; a["3"] = 3; a["4"] = 4; a["5"] = 5
a["6"] = 6; a["7"] = 7; a["8"] = 8; a["9"] = 9; a["A"] = 10; a["B"] = 11
a["C"] = 12; a["D"] = 13; a["E"] = 14; a["F"] = 15; a["a"] = 10
a["b"] = 11; a["c"] = 12; a["d"] = 13; a["e"] = 14; a["f"] = 15
}
{
for (i = 1; i <= NF; i++) {
sub(/^\$/,"",$i) # remove leading dollar signs
sub(/^0x/,"",$i) # remove leading hex indicator
if ($i !~ /^[-0-9A-Fa-f]+$/) next # skip non-hex lines
x = hex2decimal($i)
printf("%8s --> %10d\n",$i,x)
sum += x
n++
}
}
END {
if (n > 0)
printf("%08x --> %10d SUM %.2f AVG %d N\n",sum,sum,sum/n,n)
}
function hex2decimal(x, d,i,n,v,s) # hex string to decimal integer
{
d = 0
s = 1
if (substr(x,1,1) == "-") {
s = -1
x = substr(x,2)
}
n = length(x)
for (i = 0; i < n; i++) {
v = a[substr(x,n-i,1)]
d += v * 16^i
}
return s*d
}
Back to Dan Allen's home page.
Created: 13 Jul 2023
Modified: 17 Sep 2025