I have a file containing a list of hexadecimal numbers, as 0x12345678
one per line.
I want to make a calculation on them. For this, I thought of using awk
. But if printing an hexadecimal number with awk
is easy with the printf
function, I haven't find a way to interpret the hexadecimal input other than as text (or 0
, conversion to integer stops on the x
).
awk '{ print $1; }' // 0x12345678
awk '{ printf("%x\n", $1)}' // 0
awk '{ printf("%x\n", $1+1)}' // 1 // DarkDust answer
awk '{ printf("%s: %x\n", $1, $1)}' // 0x12345678: 0
Is it possible to print, e.g. the value +1?
awk '{ printf(%x\n", ??????)}' // 0x12345679
Edit: One liners on other languages welcomed! (if reasonable length ;-) )
Hex addition involves calculating basic decimal addition while converting between hex and decimal when values larger than 9 (the numerals A through F) are present. In the example above, B + 8 in decimal is 11 + 8 = 19. 19decimal is 13hex, since there is 1 set of 16, with 3 left over.
0x11. Hexadecimal 11, decimal value 17.
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.
Base-16 uses 16 values: the numbers 0 to 9 and the letters A to F. Up to the number 9 the decimal and hexadecimal systems are identical: a base-10 number 9 is also a 9 in base-16. We don't have a single number for ten, which is why base-16 uses the letters A to F. The letter A is 10, B is 11 etc.
gawk has the strtonum
function:
% echo 0x12345678 | gawk '{ printf "%s: %x - %x\n", $1, $1, strtonum($1) }'
0x12345678: 0 - 12345678
In the original nawk
and mawk
implementations the hexadecimal (and octal) numbers are recognised. gawk
(which I guess you are using) has the feature/bug of not doing this. It has a command line switch to get the behaviour you want: --non-decimal-data
.
echo 0x12345678 | mawk '{ printf "%s: %x\n", $1, $1 }'
0x12345678: 12345678
echo 0x12345678 | gawk '{ printf "%s: %x\n", $1, $1 }'
0x12345678: 0
echo 0x12345678 | gawk --non-decimal-data '{ printf "%s: %x\n", $1, $1 }'
0x12345678: 12345678
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