我需要在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) }我可以在我的打印语句中使用一种解决方法,但是如果我能做到这些,代码就会更清晰。
I need to convert a number from decimal to binary in Perl where my constraint is that the binary number width is set by a variable:
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) }I can probably use a work-around in my print statements, but the code would be much cleaner if I can do the aforementioned.
最满意答案
你的问题如下:
如何构建字符串%5b ,其中5是可变的?
使用连接。
"%".$width."b"这也可以写成
"%${width}b"在更复杂的情况下,您可能想要使用以下内容,但在这里过度使用。
join('', "%", $width, "b")请注意, sprintf接受*作为要在变量中提供的值的占位符。
sprintf("%*b", $width, $num)如果你想要前导零而不是前导空格,只需在%后面加一个0 。
Your question amounts to the following:
How do I build the string %5b where 5 is variable?
Using concatenation.
"%".$width."b"That can also be written as
"%${width}b"In more complex cases, you might want to use the following, but it's overkill here.
join('', "%", $width, "b")Note that sprintf accepts a * as a placeholder for a value to be provided in a variable.
sprintf("%*b", $width, $num)If you want leading zeroes instead of leading spaces, just add a 0 immediately after the %.
更多推荐
发布评论