How to do hexadecimal calculations with awk?

I have a file containing a list of hexadecimal numbers, like 0x12345678 one per line.

I want to make a calculation for them. For this, I thought about using awk . But if printing a hexadecimal number with awk easy using the printf function, I have not found a way to interpret hexadecimal input other than text (or 0 , converting to integer stops on 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, for example. +1 value?

 awk '{ printf(%x\n", ??????)}' // 0x12345679 

Edit: one liner in other languages โ€‹โ€‹is welcome! (if reasonable length ;-))

+4
source share
4 answers

In the original nawk and mawk implementations, hexadecimal (and octal) numbers are recognized. gawk (which I assume you are using) has a function / error without doing this. This has a command line switch to get the desired behavior: --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 
+15
source

gawk has a strtonum function:

 % echo 0x12345678 | gawk '{ printf "%s: %x - %x\n", $1, $1, strtonum($1) }' 0x12345678: 0 - 12345678 
+6
source

You might not need awk at all, as string / number conversion is hairy. Bash versions 3 and 4 are very powerful. It is often simpler, clearer and more convenient to stay in Bash, and possibly use grep, cut, etc.

For example, in Bash, hexadecimal numbers are converted naturally:

 $ printf "%d" 0xDeadBeef 3735928559 $ x='0xE'; printf "%d %d %d" $x "$x" $((x + 1)) 14 14 15 

Hope this helps.

+3
source

You can convert a string to a number simply by doing $1 + 0 . AWK automatically converts a string to a number as needed. So you can do:

 awk '{ printf "%X\n", $1+1; }' 

or if you want the designation 0x1234 :

 awk '{ printf "0x%X\n", $1+1; }' 
0
source

All Articles