awk中没有左移、右移、按位取反、按位与、按位或、按位异或的操作符,只能用函数。
lshift(val, count)、rshift(val, count)、compl(val)、and(v1, v2)、or(v1, v2)、xor(v1, v2)。
一、左移、右移、取反
1.1 文件内容
1.2 命令与结果
cat 000.txt | awk '{print lshift($1,8), rshift($1,8), compl($1), $1}'
1.3 分析:
原始数据:0x4030201 67305985
左移8位: 0x403020100 17230332160
右移8位: 0x40302 262914
按位取反:0x1FFFFFFBFCFDFE 9007199187435006【这个有点问题,有待进一步分析】
二、按位与、或、异或
2.1 文件内容
2.2 命令与结果
cat 000.txt | awk '{print and($1,$2), or($1,$2), xor($1,$2), $1, $2}'
2.3 分析
原始数据:10 0x1010
3 0x0011
按位与: 2 0x0010
按位或: 11 0x1011
按位异或: 9 0x1001
三、 一个应用实例
3.1 将数值IP(主机字节序),转为字符串IP
cat bb.txt | awk '{ip11=rshift(and($1, 0xFF000000), 24); ip12=rshift(and($1, 0xFF0000), 16); ip13=rshift(and($1, 0xFF00), 8); ip14=and($1, 0xFF); ip21=rshift(and($2,0xFF000000), 24); ip22=rshift(and($2, 0xFF0000), 16); ip23=rshift(and($2, 0xFF00), 8); ip24=and($2, 0xFF); print ip11"."ip12"."ip13"."ip14, ip21"."ip22"."ip23"."ip24, $3;}'
bb.txt:
执行结果:
3.2 将字符串IP,转为数值IP(主机字节序)
cat aa.txt | awk '{split($1, IP1, "."); ip11=lshift(IP1[1],24) + lshift(IP1[2], 16) + lshift(IP1[3], 8) + IP1[4]; split($2, IP2, "."); ip22=lshift(IP2[1], 24) + lshift(IP2[2], 16) + lshift(IP2[3], 8) + IP2[4]; print ip11, ip22, $3; }'
或者参照:http://blog.csdn.net/guowenyan001/article/details/12975609
参考资料:
怎么用awk实现位与运算操作:http://bbs.chinaunix.net/thread-1923253-1-1.html