2010-05-12 345 views
11

我想制作一个程序,将十进制数字或文本转换成Perl中的二进制数字。该程序要求用户输入一个字符或字符串,然后将结果打印到控制台。我该怎么做呢?我一直在研究的代码是在下面,但我似乎无法修复它。如何在Perl中将十进制数转换为二进制数?

print "Enter a number to convert: "; 
chomp($decimal = <STDIN>); 
print "\nConverting $number to binary...\n"; 
$remainder = $decimal%2; 
while($decimal > 0) 
{ 
    $decimal/2; 
    print $remainder; 
} 

回答

23

$decimal/2;不影响$decimal

你可能想$decimal /= 2;,或者如果你想成为冷,再$decimal >>= 1;

不过说真的,真的,你可能只是想:

printf "%b\n", $decimal;

+0

什么是/ =是什么意思,printf是做什么的?我很抱歉,即时通讯的一种新的 – David 2010-05-12 17:45:15

+3

'/ ='是除法赋值,换句话说'$ decimal/= 2'等价于'$ decimal = $ decimal/2'。 'printf'是一个格式化的打印功能。如果您真的对编程感到陌生,以至于您不熟悉这些内容,我会强烈建议您购买一本关于Perl的书以开始使用,而不是仅仅依靠向Internet发问。 – 2010-05-12 17:48:15

+0

'$ decimal/= 2;'是'$ decimal = $ decimal/2'的简写形式;' 像'$ decimal/2;'这样的行不起任何作用。这就好像有'42;' printf意思是“打印格式化”。 '%b'表示参数将在输出时转换为二进制。 – 2010-05-12 17:48:34

5

我在这些别名的.bash_profile在命令行上快速转换:

alias d2h="perl -e 'printf qq|%X\n|, int(shift)'" 
alias d2o="perl -e 'printf qq|%o\n|, int(shift)'" 
alias d2b="perl -e 'printf qq|%b\n|, int(shift)'" 
alias h2d="perl -e 'printf qq|%d\n|, hex(shift)'" 
alias h2o="perl -e 'printf qq|%o\n|, hex(shift)'" 
alias h2b="perl -e 'printf qq|%b\n|, hex(shift)'" 
alias o2h="perl -e 'printf qq|%X\n|, oct(shift)'" 
alias o2d="perl -e 'printf qq|%d\n|, oct(shift)'" 
alias o2b="perl -e 'printf qq|%b\n|, oct(shift)'" 
0
alias b2d="perl -e 'printf qq|%d\n|, unpack("N", pack("B32", substr("0" x 32 . 1101 , -32)))'" 
alias b2h="perl -e 'printf qq|%X\n|, unpack("N", pack("B32", substr("0" x 32 . 1101 , -32)))'" 
alias b2o="perl -e 'printf qq|%o\n|, unpack("N", pack("B32", substr("0" x 32 . 1101 , -32)))'" 
+1

只是代码没有解释是不是很有用。 – svick 2012-09-30 17:11:38

0
#!/usr/bin/perl 
use strict; 
print "Enter a number to convert: "; 
chomp(my $decimal = <STDIN>); 

print "\nConverting $decimal to binary...\n"; 

my @array; 
my $num; 

while($decimal >= 1) 
{ 
    if($decimal == 1) { 

     $num .= 1; 
     last; 
    } 

    my $remainder = $decimal%2; 
    $num .= $remainder; 
    $decimal = $decimal/2; 
} 

print $num."\n"; 
9

尝试此十进制到二进制的转换:

my $bin = sprintf ("%b", $dec); 

要得到每一位:

my @bits = split(//, $bin); 

然后您可以操纵每一位,更改MSB索引等等。

+0

对于前导零,例如总共8位数字,请使用'my $ bin = sprintf(“%.8b”,$ dec);'。示例:'00000001' – 2017-06-21 14:20:35

-2

请尝试下面的代码。它会工作。

#!/usr/bin/perl 

use strict; 

print "Enter a decimal number \n"; 

my $dec_number = <STDIN>; 
chomp($dec_number); 

my $reminder; 
my $result; 

while ($dec_number >= 1) 
{ 
    $reminder = $dec_number % 2;  #Modulo division to get remainder 
    $result = $reminder . $result;  #Concatenation of two numbers 
    $dec_number = $dec_number/2;  #New Value of decimal number to do next set of above operations 
} 

print "Binary number Output = ", $result, "\n"; 
相关问题