Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl decimal to binary conversion

Tags:

printf

perl

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.

like image 264
sanjay Avatar asked Aug 10 '14 18:08

sanjay


1 Answers

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 %.

like image 142
ikegami Avatar answered Oct 09 '22 08:10

ikegami