Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View Perl Variables as Bytes/Bits

Tags:

binary

perl

Disclaimer: It's been ages since I've done any perl, so if I'm asking/saying something stupid please correct me.

Is it possible to view a byte/bit representation of a perl variable? That is, if I say something like

my $foo = 'a';

I know (think?) the computer sees $foo as something like

0b1100010

Is there a way to get perl to print out the binary representation of a variable?

(Not asking for any practical purpose, just tinkering around with a old friend and trying to understand it more deeply than I did in 1997)

like image 544
Alan Storm Avatar asked Mar 12 '13 21:03

Alan Storm


1 Answers

Sure, using unpack:

print unpack "B*", $foo;

Example:

% perl -e 'print unpack "B*", "bar";'
011000100110000101110010

The perldoc pages for pack and perlpacktut give a nice overview about converting between different representations.

like image 152
speakr Avatar answered Sep 19 '22 23:09

speakr