Can you explain what I get from unpacking?

I'm relatively inexperienced with Perl, but my question is about the decompress function when getting bits for a numeric value. For instance:

my $bits = unpack("b*", 1);
print $bits;

This results in a print of 10001100, which is 140 in decimal. In reverse order, it is 49 in decimal value. Any other values ​​that I tried seem to give the wrong bits.

However, when I run $ bits through the package, it again produces 1. Is there something missing here?

I seem to have come to conclusions when I decided that my problem was resolved. Perhaps I should briefly explain what I'm trying to do.

I need to convert an integer value that can be up to 24 bits in size (the point is that it can be more than one byte) into a bit string. This can be achieved with unpack and pack, as suggested by @ikegami, but I also need to find a way to convert this string to the original integer (not a string representation).

As I mentioned, I'm relatively inexperienced with Perl, and I try without success.


I found what seems like an optimal solution:

my $bits = sprintf("%032b", $num);
print "$bits\n";
my $orig = unpack("N", pack("B32", substr("0" x 32 . $bits, -32)));
print "$orig\n";
+5
source share
6 answers

, . pack, unpack, - sprintf printf %b:

my $int = 5;
my $bits = sprintf "%024b\n", $int;
print "$bits\n";

( 0s 1s ), - oct 0b:

my $orig = oct("0b$bits");
print "$orig\n";

, unpack , , , , pack . %b .

, , :

my @binary = map { sprintf '%08b', $_ } 0 .. 255;

print $binary[$int];  # Assuming $int is between 0 and 255
+2

, : unpack("b*", 1) typecast "1", ASCII 31 ( ).

00110001, 10001100 , "b*" "b*". "" . "Endian-ness" - , .

+6

, , "endianness" . Perl 1 '1' (0x31). , 1 → 1000 ( ) 3 → 1100.

"" , Perl , , .

pack:

b A bit string (ascending bit order inside each byte, like vec()).
B A bit string (descending bit order inside each byte).

, , :

unpack( 'B*', chr(1))
+3

ord(1) 49. - sprintf("%064b", 1), .

+2

, . , 00000001.

, , , EBCDIC-. , unpack - ( ). ,

unpack('b*', pack('C', 1))

. , 10000000. 00000001

unpack('B*', pack('C', 1))  # 00000001
+1

"B" "b".

$ perl -E'say unpack "b*", "1"'
10001100

$ perl -E'say unpack "B*", "1"'
00110001

pack

0
source

All Articles