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.|
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.