Perl十进制到二进制转换

san*_*jay 3 perl printf

我需要在Perl中将数字从十进制转换为二进制,其中我的约束是二进制数宽度由变量设置:

for (my $i = 0; $i<32; $i++)
{
    sprintf("%b",$i) # This will give me a binary number whose width is not fixed
    sprintf("%5b",$i) # This will give me binary number of width 5

    # Here is what I need:
    sprintf (%b"$MY_GENERIC_WIDTH"b, $i)
}
Run Code Online (Sandbox Code Playgroud)

我可以在我的打印语句中使用解决方法,但如果我可以执行上述操作,代码将更加清晰.

Mil*_*ler 7

您可以将宽度插入格式字符串中:

my $width = 5;

for my $i (0..31) {
    printf "%${width}b\n", $i;
}
Run Code Online (Sandbox Code Playgroud)

或者使用 a*通过变量输入:

my $width = 5;

for my $i (0..31) {
    printf "%*b\n", $width, $i;
}
Run Code Online (Sandbox Code Playgroud)

两个输出:

    0
    1
   10
   11
  100
  101
  110
  111
 1000
 1001
 1010
 1011
 1100
 1101
 1110
 1111
10000
10001
10010
10011
10100
10101
10110
10111
11000
11001
11010
11011
11100
11101
11110
11111
Run Code Online (Sandbox Code Playgroud)


ike*_*ami 5

您的问题等于以下内容:

如何构建字符串%5b,其中5的变量?

使用连接.

"%".$width."b"
Run Code Online (Sandbox Code Playgroud)

那也可以写成

"%${width}b"
Run Code Online (Sandbox Code Playgroud)

在更复杂的情况下,您可能希望使用以下内容,但这在此处过度.

join('', "%", $width, "b")
Run Code Online (Sandbox Code Playgroud)

请注意,sprintf接受a *作为要在变量中提供的值的占位符.

sprintf("%*b", $width, $num)
Run Code Online (Sandbox Code Playgroud)

如果你想要前导零而不是前导空格,只需0在后面添加一个%.