Perl: for an arbitrary string, how do you extract the first N bits?

Given the string $ old_str, I am trying to extract the first N bits (not bytes) in $ new_str. I read the batch documentation and perlpacktut, but I'm hopelessly confused. This is where I stand now:

my $old_str = "9876543210";                                                     
# Extract the first 5 bits
my $new_str = pack("B5", unpack("B*", $old_str));
printf "%#b | %#b\n", $new_str, $old_str;

This gives:

0b1000 | 0b1001001100101100000001011011101010

But I want this:

0b10010 | 0b1001001100101100000001011011101010
+5
source share
3 answers

Do you want built-in vec: vec

+1
source

You can use unpack:

my $bit_string = unpack( 'b*', $old_str );

It will create a string of 80 '1 (char 0x31s) and' 0 (char 0x30s). On Windows, you probably need to add reverse.

0
source

, . unpack("B*", $old_str) , ( ):

00111001 00111000 00110111 00110110 00110101 00110100 00110011 00110010 00110001 00110000

... , , ASCII :

$ perl -E "printf('%#b ', ord) for split(//, '9876543210')"
0b111001 0b111000 0b110111 0b110110 0b110101 0b110100 0b110011 0b110010 0b110001 0b110000

Then you do pack('B5', '00111001…')that seems a bit complicated. It looks like it packreturns a byte consisting of the five rightmost bits in the first 8-tuple ( 11001). This gives 56 or a string 8(since ASCII for 8is 56):

$ perl -E "say ord pack('B5', '00111001…')"
56
$ perl -E "say pack('B5', '00111001…')"
8

And when you printfstring, you get the binary numeric number of the number 8:

$ perl -E "say printf '%#b', '8'"
0b10001

(This is madness.)

0
source

All Articles