[root@LookBack ~]# echo 8.8.8.8|awk -F. '{for(i=1;i<=NF;i++){a="";b=$i;while(b){a=b%2 a;b=int(b/2)}printf("%08d%s",a,i!=NF?".":"\n")}}'
00001000.00001000.00001000.00001000
[root@LookBack ~]#
[root@LookBack ~]#
[root@LookBack ~]# echo 8.8.8.8|awk -F. '{printf "%d\n", ($1*(2^24))+($2*(2^16))+($3*(2^8))+$4}'
134744072
[root@LookBack ~]#
[root@LookBack ~]#
[root@LookBack ~]# echo 00001000.00001000.00001000.00001000|awk -F. 'function bin2dec(a,b,i,c){b=length(a);c=0;for(i=1;i<=b;i++){c+=c;if(substr(a,i,1)=="1")c++}return c}{for(j=1;j<=NF;j++)printf("%d%s",bin2dec($j),j!=NF?".":"\n")}'
8.8.8.8
[root@LookBack ~]#
[root@LookBack ~]#
[root@LookBack ~]# echo 1000.1000.1000.1000|awk -F. 'function bin2dec(a,b,i,c){b=length(a);c=0;for(i=1;i<=b;i++){c+=c;if(substr(a,i,1)=="1")c++}return c}{for(j=1;j<=NF;j++)printf("%d%s",bin2dec($j),j!=NF?".":"\n")}'
8.8.8.8
[root@LookBack ~]#
#拆分說明
awk -F. '{ #以.做分隔字元;
for(i=1;i<=NF;i++){ #把IP分成4段,順序進入迴圈;
a=""; #定義一個變數a目前值是空;
b=$i; #定義一個變數b值是進入迴圈的值;
while(b){ #在awk裡面0為假,所以只有b≠0都進入迴圈體;
a=b%2 a; #假如b=8這裡a=0"" 這裡""就是上面定義a的作用,當下次進入b=4進入迴圈體的時候a=00了,再下次b=2進入迴圈體的時候a=000了;
b=int(b/2) #這裡就是在類比十進位轉二進位筆算那一套除以2取結果整數部分;
}
printf("%08d%s",a,i!=NF?".":"\n") #這裡其實就是if(i!=NF){printf"%08d",a}else{printf"%08d\n",a}的三目寫法,實現列印8位的二進位不足用0補;
}
}'
###下面是網上的awk實現十進位轉二進位
##https://www.cs.ucsb.edu/~sherwood/awk/decimal2binary.awk.txt
#!/usr/bin/gawk -f
# ___ _ _ ____ ___ ___ ____ ___ ____
# | \ | | | | | |__| |__] |___
# |__/ |__| |___ | | | | | |___
#
# The scripts were written to be usefull in
# a research enviornment, but anyone is welcome
# to use them. Happy awking. -Tim Sherwood
func get01string(innum,t,retstr,i) {
retstr = "";
t=innum;
while(t){
if (t%2==0) {
retstr = "0" retstr;
}
else{
retstr = "1" retstr;
}
t = int(t/2);
}
return retstr;
}
{
print get01string( $1 );
}