# Convert hex to bin

Discussion in 'Perl Misc' started by Klaus Sulzberger, Mar 12, 2007.

1. ### Klaus SulzbergerGuest

Follwing function convert Hex to bin:

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)

Klaus Sulzberger, Mar 12, 2007

2. ### Michele DondiGuest

On 12 Mar 2007 12:52:58 GMT, Abigail <> wrote:

>Is your posting the Perl equivalent of the joke of the man going to
>the doctor saying "my head hurts when I bang it against the wall"?

I think he found the function ready made, and hardly grasps what it
does. In which case he should have said so. This is not a helpdesk
anyway. ++ for the fun!

Michele
--
{\$_=pack'B8'x25,unpack'A8'x32,\$a^=sub{pop^pop}->(map substr
((\$a||=join'',map--\$|x\$_,(unpack'w',unpack'u','G^<R<Y]*YB='
..'KYU;*EVH[.FHF2W+#"\Z*5TI/ER<Z`S(G.DZZ9OX0Z')=~/./g)x2,\$_,
256),7,249);s/[^\w,]/ /g;\$ \=/^J/?\$/:"\r";print,redo}#JAPH,

Michele Dondi, Mar 12, 2007

3. ### Michele DondiGuest

On Mon, 12 Mar 2007 13:48:16 +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.

Putting '#' (without quotes) in front of one of those lines will do
what you want. Since the lines are three, you may find the right one
by trial. Incidentally, once you have done so you may avoid the \$str
variable altogether, and the sub may consist of a single statement.
This is left as an exercise, of course.

Michele
--
{\$_=pack'B8'x25,unpack'A8'x32,\$a^=sub{pop^pop}->(map substr
((\$a||=join'',map--\$|x\$_,(unpack'w',unpack'u','G^<R<Y]*YB='
..'KYU;*EVH[.FHF2W+#"\Z*5TI/ER<Z`S(G.DZZ9OX0Z')=~/./g)x2,\$_,
256),7,249);s/[^\w,]/ /g;\$ \=/^J/?\$/:"\r";print,redo}#JAPH,

Michele Dondi, Mar 12, 2007
4. ### Mumia W.Guest

On 03/12/2007 07:48 AM, Klaus Sulzberger wrote:
> Follwing function convert Hex to bin:
>
> 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)
>
>

sub hex2bin {
unpack 'B8', pack 'H2', \$_[0];
}

The "perldoc -f pack" command describes the format strings.

Mumia W., Mar 12, 2007
5. ### Michele DondiGuest

On Mon, 12 Mar 2007 14:56:23 GMT, "Mumia W."
<> wrote:

> sub hex2bin {
> unpack 'B8', pack 'H2', \$_[0];
> }
>
>The "perldoc -f pack" command describes the format strings.

Naaah, you spoon-fed him at last!

Michele
--
{\$_=pack'B8'x25,unpack'A8'x32,\$a^=sub{pop^pop}->(map substr
((\$a||=join'',map--\$|x\$_,(unpack'w',unpack'u','G^<R<Y]*YB='
..'KYU;*EVH[.FHF2W+#"\Z*5TI/ER<Z`S(G.DZZ9OX0Z')=~/./g)x2,\$_,
256),7,249);s/[^\w,]/ /g;\$ \=/^J/?\$/:"\r";print,redo}#JAPH,

Michele Dondi, Mar 12, 2007
6. ### Mirco WahabGuest

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

Mirco Wahab, Mar 12, 2007
7. ### Mirco WahabGuest

Mumia W. wrote:
>
> sub hex2bin {
> unpack 'B8', pack 'H2', \$_[0];
> }
>

another possibility would be:

...

sub hex2bin {
base_convert (shift), 16, 2
}

...

(OK, I said "possibility") ...

Regards

Mirco

Mirco Wahab, Mar 12, 2007
8. ### A. Sinan UnurGuest

Michele Dondi <> wrote in
news:

> On Mon, 12 Mar 2007 14:56:23 GMT, "Mumia W."
> <> wrote:
>
>> sub hex2bin {
>> unpack 'B8', pack 'H2', \$_[0];
>> }
>>
>>The "perldoc -f pack" command describes the format strings.

>
> Naaah, you spoon-fed him at last!

Oh, but that's what he does.

Anyway, did I understand the question correctly? One has something like:

my \$s = 'deadbeaf';

and wants its binary representation. Why go through all the contortions
with pack/unpack?

C:\Home\asu1> perl -e "printf qq{%32.32b\n}, hex 'deadbeef'"
11011110101011011011111011101111

Sinan

--
A. Sinan Unur <>
(remove .invalid and reverse each component for email address)
clpmisc guidelines: <URL:http://www.augustmail.com/~tadmc/clpmisc.shtml>

A. Sinan Unur, Mar 13, 2007
9. ### Mumia W.Guest

On 03/12/2007 12:49 PM, Mirco Wahab wrote:
> Mumia W. wrote:
>>
>> sub hex2bin {
>> unpack 'B8', pack 'H2', \$_[0];
>> }
>>

>
> another possibility would be:
>
> ...
>
> sub hex2bin {
> base_convert (shift), 16, 2
> }
>
> ...
>
>
>
> (OK, I said "possibility") ...
>
> Regards
>
> Mirco

That's interesting. What module is "base_convert" a part of?

Yahoo-ing online, I've been able to find a base_convert() for PHP, but
not for Perl.

Mumia W., Mar 13, 2007
10. ### Mirco WahabGuest

Mumia W. wrote:
> On 03/12/2007 12:49 PM, Mirco Wahab wrote:
>> another possibility would be:
>> ...
>>
>> sub hex2bin {
>> base_convert (shift), 16, 2
>> }
>>
>> ...
>> (OK, I said "possibility") ...

>
> That's interesting. What module is "base_convert" a part of?
> Yahoo-ing online, I've been able to find a base_convert() for PHP, but
> not for Perl.

I wrote this because *I think* such
a simple number base conversion
'core functionality' is missing
from Perl (but is available in
PHP).

There is a module Math::BaseCalc
which appears to do that - but
doesn't work that intuitive (no core).

The interface would be like (fictional):

use Numbers::Base qw 'convert'; # core

sub my_hex2bin {
convert (shift), 16, 2
}

Maybe there is already something
appropriate I missed? Perl6?

Regards

Mirco

Mirco Wahab, Mar 13, 2007
11. ### Mirco WahabGuest

Mumia W. wrote:
> That's interesting. What module is "base_convert" a part of?
>
> Yahoo-ing online, I've been able to find a base_convert() for PHP, but
> not for Perl.

I wrote this because *I think* such
a simple number base conversion
'core functionality' is missing
from Perl (but is available in
PHP).

There is a module Math::BaseCalc
which appears to do that - but
doesn't work that intuitive (no core).

The interface would be like (fictional):

use Numbers::Base qw 'convert'; # core

sub my_hex2bin {
convert shift, 16, 2
}

Maybe there is already something
appropriate I missed? Perl6?

Regards

Mirco

Mirco Wahab, Mar 13, 2007
12. ### Uri GuttmanGuest

>>>>> "MW" == Mumia W <> writes:

>> sub hex2bin {
>> base_convert (shift), 16, 2
>> }

MW> That's interesting. What module is "base_convert" a part of?

MW> Yahoo-ing online, I've been able to find a base_convert() for PHP, but
MW> not for Perl.

check Math::BaseCnv (on cpan) and its cnv() function. it will convert
any base number to any base and also do some smart guessing for you. and
it can export some common variation subs too.

i just discovered it while helping a client with hex to base36
conversions.

as for having general base conversions in core, let php have the
bloat. perl already can convert between binary, octal, decimal and hex
in core and in multiple ways (sprintf, hex, oct, pack/unpack). the rest
should be a module as it is.

uri

--
Uri Guttman ------ -------- http://www.stemsystems.com
--Perl Consulting, Stem Development, Systems Architecture, Design and Coding-
Search or Offer Perl Jobs ---------------------------- http://jobs.perl.org

Uri Guttman, Mar 13, 2007
13. ### Mirco WahabGuest

Uri Guttman wrote:
> check Math::BaseCnv (on cpan) and its cnv() function. it will convert
> any base number to any base and also do some smart guessing for you. and
> it can export some common variation subs too.

Thanks for that hint (why didn't I find it?) ...

> i just discovered it while helping a client with
> hex to base36 conversions.

Good.

> as for having general base conversions in core, let php have
> the bloat. perl already can convert between binary, octal,
> decimal and hex in core and in multiple ways (sprintf, hex,
> oct, pack/unpack). the rest should be a module as it is.

OK, you like it as it is. But to have a "central
conversion" location in core, which does the obvious
things (hex, oct etc.) if possible and "digs deep"
if necessary - wouldn't be that bad imho.

With this in mind, the OP could have used
for example

...

use Math::BaseCnv;

sub base_convert {
cnv @_
}

my \$hnum = '7D';
my \$bnum = base_convert \$hnum, 16, 2;

printf "%0*s", 4*length(\$hnum), \$bnum;

...

Regards & thanks

Mirco

Mirco Wahab, Mar 13, 2007

### Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.