Re: Convert hex to bin
- From: Mirco Wahab <wahab-mail@xxxxxx>
- Date: Mon, 12 Mar 2007 18:04:46 +0100
Klaus Sulzberger wrote:
sub hex2bin
{
my $str=unpack("B32",pack("N",hex$_[0]));
$str=~s/^0+(?=\d)//;
return($str);
}
The problem of the function is, that the result cuts the zeros.
For examples:
Hex: 7D
Function result: 1111101
Want to have: 01111101
(for 1 Byte)
Aside from the fun part, you
can of course 'hand craft' such
a functionality *without any*
of Perl's appropriate builtins,
like:
...
sub hax2bin {
my $BS = {
0=>'OOOO', 1=>'OOOL', 2=>'OOLO', 3=>'OOLL' ,
4=>'OLOO', 5=>'OLOL', 6=>'OLLO', 7=>'OLLL' ,
8=>'LOOO', 9=>'LOOL', A=>'LOLO', B=>'LOLL' ,
C=>'LLOO', D=>'LLOL', E=>'LLLO', F=>'LLLL'};
join ':', map $BS->{ $_ }, split //, $1
if (shift) =~ / (?:0x)? (.+) /x
}
my $hnum = '0xA1A2';
my $bnum = hax2bin $hnum;
print $bnum;
...
if you really need 'very special' mappings.
Regards
Mirco
.
- References:
- Convert hex to bin
- From: Klaus Sulzberger
- Convert hex to bin
- Prev by Date: Re: Non-blocking directory watching
- Next by Date: Re: Equivalent in Perl
- Previous by thread: Re: Convert hex to bin
- Next by thread: Flush buffer combined with mod_deflate doesn't seem to work
- Index(es):
Relevant Pages
|