Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I am attempting to make a binary to hexadecimal number converter--however the catch is that I want it to convert an arbirtrarily long string of 0s and 1s. I'm using the fact that grouping the 0s and 1s into pairs of 4s will allow for quick and easy conversion, however I'm getting some errors. (p.s., I should probably should say that this is a golf attempt, to explain myself(you'll see)). The code's here, though I break it up to attempt to explain my logic:
$_="10101010000011110101000101001110110010100111"; (reverse, #I need it reversed so what follows will work s/(.)(.)(.)(.)/ #get the four digits && store them $a+=2**($_-1)if$$_/ee #take two to the $_power if #$$_ exists(e.g., $1 set, $2 set,etc) for 1..4 && #do it for each digit and s/1(?=\d)// && y/0-5/a-f/) #if 2-digit answer convert #to appropriate letter for hex for split /(....)/; #do this for all 4 digits #in $_ print $a, "\n";
Here's the code, minus the comments, so it appears somewhat(hopefully) clearer now that you understand what I'm trying to do.
$_="10101010000011110101000101001110110010100111"; (reverse,s/(.)(.)(.)(.)/$a+=2**($_-1)if$$_/ee for 1..4 && s/1(?=\d)// && y/0-5/a-f/) for split /(....)/; print $a, "\n";
using g++, here's the error I get:
|syntax error at bin2hex.pl line 3, near "s/(.)(.)(.)(.)/$a+=2**($_-1)if$$_/ee for "
Execution of bin2hex.pl aborted due to compilation errors.|

Replies are listed 'Best First'.
Re: bin2hex converter
by Abigail (Deacon) on Jun 10, 2001 at 21:11 UTC
    Eh, is there a reason not to use pack/unpack? Assuming $_ contains a multiple of 8 bits (else, prepad with 0's), the following converts binairy to hexadecimal:
    $hex = unpack ("H*", pack ("B*", $_));

    -- Abigail

      No reason in particular. . . just trying it for fun. I was seeing how small I could get the code w/o using pack/unpack/modules
        Oh, you wanted to play golf? Well, how about:
        s/(.{1,4})(?=(?:.{4})*$)/sprintf"%x",eval"0b$1"/eg;

        -- Abigail

Re: bin2hex converter
by Vynce (Friar) on Jun 11, 2001 at 00:45 UTC

    well, aside from abigail's golfing, i think i should point out that, while it may not be causing your syntax error, this piece of code:

    s/(.)(.)(.)(.)/$a+=2**($_-1)if$$_/ee for 1..4
    represents a logical error. what are you performing the s/// on? $_. you explicitly set $_ above, but you are resetting it in the for loop. so this won't work; it will try to match each of 1..4 against /..../ and fail every time because none of them is 4 digits long.

    i believe your syntax error, though, is in the fact that you are using && after the inline for loop. or maybe there should only be one /e. or maybe i'm barking up the wrong tree; but there's something to work on. i find, when golfing, that it helps to write the algorithm out long-way and shorten it a bit at a time (or a byte at a time) as i go.

    .