Re: hex represenation from string in perl



In article <1126029907.731527.198410@xxxxxxxxxxxxxxxxxxxxxxxxxxxx>,
<"archilleswaterland@xxxxxxxxxxx"> wrote:

> hi,
>
> I am sorry. I tried reading the FAQ, too cryptic. I am not writing here
> out of laziness and wanting a direct answer.
> It is out of frustration and wanting to learn. I looked at a lot of
> documentation - pack, unpack, int, hex ... perldoc -f ...
>
> #!usr/bin/perl -w
>
> use strict;
>
> my @file;
> my $v;
> my $i;
>
> open(FILE,"< values") or die "cannot open file for reading: $!";
> @file = <FILE>;
> close (FILE) or die "an error occured while trying to close the file:
> $!";
> print ("@file");
> print ("\n");
>
> foreach $v (@file){
> chomp($v);
> printf ("%0.4x ",$v);
> }
>
> it shoudn't be hard at all write, I am reading in a string/variable
> 1111 and I want to print out f
> this still doesn't work : (
>

What about the following is cryptic?

<faq>

How do I convert from binary to decimal
Perl 5.6 lets you write binary numbers directly with the 0b nota-
tion:

number = 0b10110110;

Using oct:

my $input = "10110110";
$decimal = oct( "0b$input" );

Using pack and ord:

$decimal = ord(pack('B8', '10110110'));

</faq>

What was wrong with the suggestion John gave you?

Your program isn't working because you are not converting the strings
of 0s and 1s to a binary number, therefore, they are being treated as
decimal numbers.

Here is a slightly expanded form of John's suggestion using the
convenient DATA file handle:

#!/usr/local/bin/perl
#
use warnings;
use strict;

while(<DATA>) {
chomp;
my $val = oct "0b$_";
printf "%s = %x\n", $_, $val;
}
__DATA__
1111
1100
1001


See if you can get that to work.

Posted Via Usenet.com Premium Usenet Newsgroup Services
----------------------------------------------------------
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
----------------------------------------------------------
http://www.usenet.com
.



Relevant Pages