Perl decimal to binary conversion

I need to convert a number from decimal to binary in Perl, where my limitation is that the width of the binary number is given 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 may be using bypass in my print statements, but the code will be much cleaner if I can do the above.

+3


source to share


2 answers


Your question boils down to this:

How do I plot a string %5b

where 5

is a variable?

Using concatenation.

"%".$width."b"

      

This can also be written as

"%${width}b"

      



For more complex cases, you can use the following, but it overflows here.

join('', "%", $width, "b")

      

Note that it sprintf

takes *

as a placeholder for the value to be supplied to the variable.

sprintf("%*b", $width, $num)

      

If you want leading zeros instead of leading spaces, just add 0

immediately after %

.

+5


source


You can interpolate the width to a format string:

my $width = 5;

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

      

Or use *

to inject it through a variable:



my $width = 5;

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

      

Both outputs:

    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

      

+4


source







All Articles