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.
Your question amounts to the following:
How do I build the string
%5b
where5
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 %
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With