View Perl variables as bytes / bits

Disclaimer: It has been a long time since I did some kind of perl, so if I ask / say something stupid, please correct me.

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

my $foo = 'a';

I know (think?) That the computer sees $foosomething like

0b1100010

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

(Without asking for any practical purpose, just mess with an old friend and try to understand him deeper than in 1997)

+5
source share
5 answers

Of course using unpack :

print unpack "B*", $foo;

Example:

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

perldoc pack perlpacktut .

+12

, , "perlguts". perldoc perlguts, : http://perldoc.perl.org/perlguts.html

+2

, , , Devel:: Peek Dump, . , , .

$ perl -MDevel::Peek -e 'my $foo="a";Dump $foo';
SV = PV(0x7fa8a3004e78) at 0x7fa8a3031150
  REFCNT = 1
  FLAGS = (PADMY,POK,pPOK)
  PV = 0x7fa8a2c06190 "a"\0
  CUR = 1
  LEN = 16

$ perl -MDevel::Peek -e 'my %bar=(x=>"y",a=>"b");Dump \%bar'
SV = IV(0x7fbc5182d6e8) at 0x7fbc5182d6f0
  REFCNT = 1
  FLAGS = (TEMP,ROK)
  RV = 0x7fbc51831168
  SV = PVHV(0x7fbc5180c268) at 0x7fbc51831168
    REFCNT = 2
    FLAGS = (PADMY,SHAREKEYS)
    ARRAY = 0x7fbc5140f9f0  (0:6, 1:2)
    hash quality = 125.0%
    KEYS = 2
    FILL = 2
    MAX = 7
    RITER = -1
    EITER = 0x0
    Elt "a" HASH = 0xca2e9442
    SV = PV(0x7fbc51804f78) at 0x7fbc51807340
      REFCNT = 1
      FLAGS = (POK,pPOK)
      PV = 0x7fbc5140fa60 "b"\0
      CUR = 1
      LEN = 16
    Elt "x" HASH = 0x9303a5e5
    SV = PV(0x7fbc51804e78) at 0x7fbc518070d0
      REFCNT = 1
      FLAGS = (POK,pPOK)
      PV = 0x7fbc514061a0 "y"\0
      CUR = 1
      LEN = 16
+2

:

printf "%v08b\n", 'abc';

:

01100001.01100010.0110001

( v - printf/sprintf perl, , b.)

This differs from the decompression offer, where there are characters that exceed "\xff": the decompression will return only 8 low bits (with a warning), it printf '%v...'will show all bits:

$ perl -we'printf "%vX\n", "\cA\13P\x{1337}"'
1.B.50.1337
+2
source

You can use ordto return the numeric value of a character and printfwith a format %bto display that value in binary format.

print "%08b\n", ord 'a'

Output

01100010
+1
source

All Articles