Perl十进制转换为二进制(Perl decimal to binary conversion)

编程入门 行业动态 更新时间:2024-10-28 12:19:17
Perl十进制转换为二进制(Perl decimal to binary conversion)

我需要在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 %.

更多推荐

本文发布于:2023-07-23 02:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1226596.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   十进制   Perl   conversion   binary

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!