Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

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 | 0b1001001100101100000001011011101010

But I want this:

0b10010 | 0b1001001100101100000001011011101010
like image 555
t.bardo Avatar asked Nov 14 '22 06:11

t.bardo


1 Answers

You want the vec built-in: vec

like image 93
ennuikiller Avatar answered May 22 '23 01:05

ennuikiller