Linux之awk实现ip地址转二进制和数字模式&十进制转二进制

  • A+
所属分类:AWK使用笔记  Linux  随手小记
摘要

在和朋友聊天的时候他说http://1743466023就是百度,我一看不就是十进制的ip地址么,然后自己就蛋疼的想用awk实现一把,于是就有了这篇博文

[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 );
}
lookback

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: