Re: Convert hex to bin



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
.



Relevant Pages

  • Re: Convert hex to bin
    ... On 03/12/2007 07:48 AM, Klaus Sulzberger wrote: ... The problem of the function is, that the result cuts the zeros. ... Hex: 7D ...
    (comp.lang.perl.misc)
  • Trying to pad a 40 digit number with zeros with no luck
    ... I found printf and typeset -Z but have had no luck getting them to ... I am pulling a 10 character Hex value from a database, ... the cases where the beginning of the Hex is zeros. ...
    (comp.unix.shell)
  • Re: Trying to pad a 40 digit number with zeros with no luck
    ... I found printf and typeset -Z but have had no luck getting them to ... I am pulling a 10 character Hex value from a database, ... the cases where the beginning of the Hex is zeros. ...
    (comp.unix.shell)
  • Re: Trying to pad a 40 digit number with zeros with no luck
    ... I am working on a script in SCO using the Korn shell. ... I found printf and typeset -Z but have had no luck getting them to ... Then I have to convert it back to Hex again and import it back into ... the cases where the beginning of the Hex is zeros. ...
    (comp.unix.shell)
  • Re: RosAsm
    ... wolfgang kern wrote: ... > I'll extend with zeros to get 32 bytes right now. ... don't see any reason why Rene would ever want to do that, ... C1 80" _should_ work to put hex straight into the code, ...
    (alt.lang.asm)