Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: unpack Binary FAIL

by ikegami (Patriarch)
on Aug 08, 2025 at 02:35 UTC ( [id://11165989]=note: print w/replies, xml ) Need Help??


in reply to unpack Binary FAIL

You want unpack "B*" (not unpack "b*"), and it requires packed bytes.

$ perl -Mv5.14 -e' my $scabyte = 0x41; say unpack "B*", pack "C*", $scabyte; ' 01000001

When you already have unpacked bytes, you can use sprintf "%b".

$ perl -Mv5.14 -e' my $scabyte = 0x41; say sprintf "%08b", $scabyte; ' 01000001

#!/usr/bin/perl use v5.14; use warnings; my $packed_bytes = "ABCD"; my @bytes = unpack 'C*', $packed_bytes; my $bin = ''; for my $byte ( @bytes ) { printf "Decimal = [%1\$d] Hex = [%1\$02X] Binary = [%1\$08b]\n", $byte; $bin .= sprintf( "%08b", $byte ); } say ""; say $bin;
Decimal = [65] Hex = [41] Binary = [01000001] Decimal = [66] Hex = [42] Binary = [01000010] Decimal = [67] Hex = [43] Binary = [01000011] Decimal = [68] Hex = [44] Binary = [01000100] 01000001010000100100001101000100

#!/usr/bin/perl use v5.14; use warnings; my $packed_bytes = "ABCD"; my $bin = unpack "B*", $packed_bytes; say $bin;
01000001010000100100001101000100

Replies are listed 'Best First'.
Re^2: unpack Binary FAIL
by marinersk (Priest) on Aug 08, 2025 at 03:45 UTC

    Thank you! I suspected it would be a basic error -- wrong tool for the job.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11165989]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (3)
As of 2026-04-19 21:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.