hi,
I wanted to convert a long binary string to a hexadecimal string. sprintf didn't work because the number was more than 32 bits and thr pack/unpack functions are very complicated for me to understand. hence, I converted it using a truth table. The code is
sub Bin2Hex{
my %truth_table = (
'0000' => '0' ,
'0001' => '1' ,
'0010' => '2' ,
'0011' => '3' ,
'0100' => '4' ,
'0101' => '5' ,
'0110' => '6' ,
'0111' => '7' ,
'1000' => '8' ,
'1001' => '9' ,
'1010' => 'A' ,
'1011' => 'B' ,
'1100' => 'C' ,
'1101' => 'D' ,
'1110' => 'E' ,
'1111' => 'F' ,
);
my $count = 0;
my $hex_string = '';
my $len = $#_ ;
#print "len $len" ;
my $nibble = '' ;
my $abit ;
my $hex_len ;
my $hex_nibble ;
$hex_len = ceil($len/4) ;
#print "hex len $hex_len \n" ;
for(my $i=0; $i < $hex_len ; $i++) {
for(my $j= 0 ; $j < 4; $j++){
$abit = pop(@_) ;
if (defined $abit) {
$nibble = $abit.$nibble;
}
else {
$nibble = '0'.$nibble ;
}
}
$hex_nibble = $truth_table{$nibble} ;
$hex_string = $hex_nibble.$hex_string ;
$nibble = '' ;
}
#print "the converted hex : $hex_string" ;
return $hex_string ;
}
the input to the function is binary string stored in list.
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.