Hex to Decimal in AWK
Learn how to convert hexadecimal (hex) numbers to decimal format using the powerful AWK scripting language. Whether you’re processing log files, parsing network data, or building CLI tools, AWK provides a fast, portable way to handle base conversions in Unix-based environments.
Why Convert Hex to Decimal in AWK?
AWK is widely used in shell scripting and data processing. Hexadecimal values often appear in:
- System logs
- Memory dumps
- Binary protocols
- Web server timestamps
Converting these hex values to decimal using AWK allows for quick inline processing without relying on external tools.
How to Convert Hex to Decimal in AWK
Method 1: Using printf
with format specifier
This is the simplest way to convert a hex value into decimal:
echo "0x1A" | awk '{ printf "%d\n", strtonum($1) }'
# Output: 26
strtonum()
converts the string to a number."%d"
formats it as a decimal.
Want to convert in reverse? Try our Decimal to Hex Converter.
Method 2: Manually Parse Hex Characters in AWK
For environments where strtonum()
isn’t available (older AWK versions):
echo "1A" | awk '
function hex2dec(h, i, d, n, c) {
n = 0
for (i = 1; i <= length(h); i++) {
c = substr(h, i, 1)
if (c ~ /[0-9]/) d = c
else d = index("ABCDEF", toupper(c)) + 9
n = n * 16 + d
}
return n
}
{ print hex2dec($1) }'
# Output: 26
This version manually calculates the decimal value by walking through each character.
For binary-level bit control, see our Hex Bitwise Calculator.
Example Use Case – Parsing Log Files with Hex IDs
Imagine a log file like this:
UserID: 0x2F4, Time: 0x5F3759DF
You can extract and convert all hex fields:
awk '{
match($0, /0x[0-9A-Fa-f]+/, m)
printf "Decimal: %d\n", strtonum(m[0])
}' logfile.txt
This script pulls the first hex value from each line and prints its decimal form.
Need to convert a hex timestamp to a readable date? Use our Hex to Date Converter.
FAQs – AWK & Hexadecimal Processing
Q1: Can AWK handle lowercase and uppercase hex?
Yes, both formats (0x1A
, 0x1a
) are supported in GNU AWK with strtonum()
. Manual parsing should convert input using toupper()
.
Q2: What if my AWK version doesn’t support strtonum()
?
You can use the manual conversion function shown above, or consider installing gawk
(GNU AWK) for modern support.
Q3: Can AWK convert hex strings without the 0x
prefix?
Yes. Just ensure your function handles raw hex input or prepend 0x
before passing to strtonum()
.