Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Convert ASCII string to 7-bit binary string

by AppleFritter (Vicar)
on Oct 27, 2015 at 22:17 UTC ( [id://1146183]=note: print w/replies, xml ) Need Help??


in reply to Convert ASCII string to 7-bit binary string

Here's another regex-based solution:

$string = '4B'; ($out = $string) =~ s/(.)/unpack 'B8', $1/eg;

Fairly straightforward, actually - this globally (/g) matches every character ((.)), executes (/e) the embedded snippet of code, and replaces the matched character with the result of the call to unpack.

EDIT: please see below for a version that actually works properly.

Replies are listed 'Best First'.
Re^2: Convert ASCII string to 7-bit binary string
by Pascal666 (Scribe) on Oct 27, 2015 at 22:21 UTC
    Problem is, that doesn't actually work. That outputs "0011010001000010" instead of "01101001000010".

      Mea culpa; I should pay more attention, and not just assume that two similar-looking binary strings are, in fact, the same. Thanks for the correction.

      Fortunately it's easily-fixed; just use substr in the substitution to chop off the first character:

      ($out = $string) =~ s/(.)/substr unpack('B8', $1), 1/eg;
        Seems like a weird way of writing the following to me:
        $out = map { substr unpack('B8', $1), 1 } $string =~ /./g;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (4)
As of 2024-04-25 16:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found