全部博文(1144)
分类: LINUX
2010-09-23 21:08:32
Issue and description:
----------------------------------------------------------------------------------------------------------------------------
perl 各种进制的转换
Solution:
----------------------------------------------------------------------------------------------------------------------------
1,十进制和二进制之间的转换:
要将10进制转换成2进制,首先将其按照网络字节顺序打包,然后逐位解包:例如:
/home/lee#perl -
$dec=10;
$bin=unpack("B32",pack("N",$dec));
print "$bin ";
__END__
00000000000000000000000000001010
2:将二进制转换成十进制:
将二进制转换成十进制,可以反过来操作:如:
/home/lee#perl -
$dec=unpack("N",pack("B32",00000000000000000000000000000011));
print "$dec ";
__END__
2147483648
PS:用这样的方法转换字符必需要32位.
3:十进制和八进制之间转换:
用perl的sprintf函数即可:如:
/home/lee#perl -e 'printf sprintf "%lo ",20'
24
4:八进制和十进制之间转换:
用perl的oct函数即可:如:
/home/lee#perl -e 'print oct 24," "'
20
5:十进制和十六进制之间转换:
利用perl的sprintf函数,附带%x转换符即可:如:
/home/lee#perl -e 'print sprintf "%x ",255'
ff
6十六进制和十进制转换:
用perl的hex函数即可实现 ,如:
/home/lee#perl -e 'print hex 0xA," "'
16