Question

simple thing, how to print a binary number and shift it to the left?

$num = 0b00000010001;
for(0..6){
    print sprintf ("%b",$num), "\n";
    $num<<1;
}

problem of this code: it doesn't print the 0's before 1! the resoult of print is just "10001", and it doesn't shift the number.

the final output should be:

00000010001
00000100010
00001000100
00010001000
00100010000
01000100000
10001000000
Was it helpful?

Solution

Just tell the formatter that you need to print exactly N (11) digits in any case, and that 0 should be used as a padding symbol:

my $num = 0b00000010001;
for (0..6) {
    printf("%011b\n", $num);
    $num <<= 1;
}

Demo.

Two sidenotes here

  • First, it's obviously redundant to do print sprintf: printf will replace it quite well.

  • Second, in the original code you forgot to assign the result of shifting back to $num. Had you started your script with the use warnings pragma (like in my demo), you'd have been notified about it with Useless use of left bitshift (<<) in void context...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top