Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

hex - How to make calculations on hexadecimal numbers with awk?

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
", $1)}'             // 0
awk '{ printf("%x
", $1+1)}'           // 1                 // DarkDust answer
awk '{ printf("%s: %x
", $1, $1)}'     // 0x12345678: 0

Is it possible to print, e.g. the value +1?

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

Edit: One liners on other languages welcomed! (if reasonable length ;-) )

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", $1, $1 }'
0x12345678: 12345678

echo 0x12345678 | gawk '{ printf "%s: %x
", $1, $1 }'
0x12345678: 0

echo 0x12345678 | gawk --non-decimal-data '{ printf "%s: %x
", $1, $1 }'
0x12345678: 12345678

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...