Perl: Given an arbitrary string, how do you extract the first N bits?
Given a string $old_str, I am trying to extract the first N bits (not bytes) into $new_str. I have been reading the pack documentation and perlpacktut, but am hopelessly confused. This is where I currently stand:
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 produces:
0b1000 | 0b1001001100101100000001开发者_JAVA技巧011011101010
But I want this:
0b10010 | 0b1001001100101100000001011011101010
You want the vec built-in: vec
You can use unpack
:
my $bit_string = unpack( 'b*', $old_str );
It will create a string of 80 '1's (char 0x31s) and '0's (char 0x30s). On Windows, you will probably need to add reverse
.
I’m not sure what you are trying to do here. The unpack("B*", $old_str)
creates a bit string containing the following bits (spaces added for readability):
00111001 00111000 00110111 00110110 00110101 00110100 00110011 00110010 00110001 00110000
…in other words, a bit string corresponding to ASCII numbers for your characters:
$ perl -E "printf('%#b ', ord) for split(//, '9876543210')"
0b111001 0b111000 0b110111 0b110110 0b110101 0b110100 0b110011 0b110010 0b110001 0b110000
Then you do pack('B5', '00111001…')
which seems to be a bit complex. It looks like pack
returns a byte consisting of the five rightmost bits in the first 8-tuple (11001
). That gives 56 or the 8
string (since the ASCII for 8
is 56):
$ perl -E "say ord pack('B5', '00111001…')"
56
$ perl -E "say pack('B5', '00111001…')"
8
And when you printf
the string, you get the binary numeric representation of the number 8:
$ perl -E "say printf '%#b', '8'"
0b10001
(This is crazy.)
精彩评论