hex represenation from string in perl

  • Thread starter archilleswaterland
  • Start date
A

archilleswaterland

Hi,

I have a file with the following contents

1111
1100
1001
..
..
..

I read it into an array and want to represent it as hex.

so I want the output to read

f
c
9
..
..
..

Any suggestions ?

thanks,
Newbie

-------------------------
#!usr/bin/perl

$file_name= <~/values>;
open(file_handler,$file_name);
@arr_file_content= <file_handler>;
close (file_handler);

print ("@arr_file_content");

foreach $v (@arr_file_content){
chomp;
printf("%0x\n",int($v));
}

this doesn't work,

-----------------
 
A

A. Sinan Unur

in
[ Please read the posting guidelines for this group. ]
I have a file with the following contents

1111
1100
1001 ....
so I want the output to read

f
c
9 ....

#!usr/bin/perl

use strict;
use warnings;

missing.
$file_name= <~/values>;

I am curious, what do you think this line does?
open(file_handler,$file_name);

Always, yes *always* check if open succeeded.
@arr_file_content= <file_handler>;

No need to read the whole file into memory if you are going to process
it line by line.
close (file_handler);

Do also check if close succeeded.
print ("@arr_file_content");

foreach $v (@arr_file_content){
chomp;
printf("%0x\n",int($v));
}

Do always check the FAQ before posting a question:

perldoc -q convert

Sinan
 
J

Joe Smith

A. Sinan Unur said:
Do also check if close succeeded.

Check for error on close() of file handle opened for output: check.
Check for error on close() of file handle opened for input: Why?
-Joe
 
A

A. Sinan Unur

Check for error on close() of file handle opened for output: check.
Check for error on close() of file handle opened for input: Why?

If close on a file opened for read fails, something must be very seriously
wrong. I do not know under which conditions such a failure might occur,
but I figure I would not want my application to continue under such
circumstances.

Probably paranoid and useless behavior.

Sinan
 
J

John W. Krahn

I have a file with the following contents

1111
1100
1001
.
.
.

I read it into an array and want to represent it as hex.

so I want the output to read

f
c
9
.
.
.

Any suggestions ?

$ echo "1111
1100
1001" | perl -lne'printf "%x\n", oct "0b$_" unless /[^01]/'
f
c
9


John
 
A

archilleswaterland

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 : (
 
P

Paul Lalli

I am sorry.

But not sorry enough to do as requested, it seems.

You still have not read the Posting Guidlines for this group. Or, you
have but have chosen not to follow them. They are posted twice a week.
If you can't find them on your news server, use Google Groups' archive
to find them.
I tried reading the FAQ, too cryptic.

Be more specific. Which FAQ did you read, and in what way did you find
it too cryptic? What part did you not understand.
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 ...

And which part of these were unclear to you as well?
#!usr/bin/perl -w

That shebang looks mighty suspicious. Are you running your script from
the root directory? Or do you have a usr/bin/ in your current
directory? Or are you retyping instead of copy and pasting?
use strict;

my @file;
my $v;
my $i;

Your variables should always be declared in the smallest scope
possible.
open(FILE,"< values") or die "cannot open file for reading: $!";

Please use lexical filehandles and the three-argument form of open.
open my $file, '<', 'values' or die "Can't open values: $!";
@file = <FILE>;

As suggested in a previous response, there is no reason to read your
entire file into memory just to process it line by line later on. Use a

close (FILE) or die "an error occured while trying to close the file:
$!";
print ("@file");

Weren't you curious as to why you got extra spaces in your output?

perldoc -q spaces
print ("\n");

foreach $v (@file){
chomp($v);
printf ("%0.4x ",$v);
}

$v is a string consisting of digits, for example '1111'. This line
takes the number one thousand, one hundred and eleven and converts it
into its hexadecimal representation.

You want a function that you can tell "this string consists of binary
data. Give me the number it represents". Now, just from experience
reading this group, I would guess that involves the use of pack()
and/or unpack(). However, I assure you I am 100% pack-clueless. I've
never understood it. I've read the docs, I've read the tutorials, I
just can't grok it.

Be that as it may, however, I did decide to check the FAQ to see if
this all-too-common task has been asked about before. I typed:
perldoc -q bits
and I was given the following question:
How do I convert bits into ints?

Well, low and behold, that's exactly what we're trying to do! The
answer given in that FAQ is:
$decimal = unpack('c', pack('B8', '10110110'));

Okay. Let's try that with your data:
$decimal = unpack('c', pack('B8', '0110'));

Hrm. 96? That doesn't seem quite right. However, I do note that
01100000 *is* the representation for 96. Is it possible that this
pack() magic is auto-padding the right-hand part of the string with 0s
until it has a full byte? Certainly seems that way. Let's try
specifying the full byte:
$decimal = unpack('c', pack('B8', '00000110'));
Ah! There we go! Now we get our correct answer of 6!

Well, now that we know the correct pack/unpack incantation, this
shouldn't be too hard...
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 : (

"doesn't work" is a phenomenally unhelpful error description. Once
again, please READ the Posting Guidelines for this group.

#!/usr/bin/perl
use strict;
use warnings;
while (my $bits = <DATA>){
chomp($bits);
$bits = '0000' . $bits if length $bits == 4;
my $dec = unpack ('c', pack('B8', $bits));
my $hex = sprintf '%.4x', $dec;
#the intermediary step could be eliminated by
#using 'h' as the unpack template instead of 'c'
print "$bits ==> $dec ==> $hex\n";
}

__DATA__
1111
0101
0110
1010
01101111

Paul Lalli
 
P

Paul Lalli

Jim said:
<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>

Er. Out of curiousity, what version of Perl is this? That FAQ is not
on my system (This is perl, v5.6.1 built for sun4-solaris), nor is it
at http://perldoc.perl.org/perlfaq.html

Paul Lalli
 
A

A. Sinan Unur

I am sorry. I tried reading the FAQ, too cryptic. I am not writing here
out of laziness

Yes you are. Accept that you are lazy. Do not compund your sins by lying.
#!usr/bin/perl -w

use warnings;

is preferable in general.
use strict;

my @file;
my $v;
my $i;

Declare variables in the smallest possible scope.
open(FILE,"< values") or die "cannot open file for reading: $!";


In general, prefer lexical filehandles and the three argument form of
open:

open my $input, '<', 'values' or die "Cannot open 'values': $!";
@file = <FILE>;

No need to read the whole file into an array only to process it line by
line later.
close (FILE) or die "an error occured while trying to close the file:
$!";

Following my insane advice I see :)
print ("@file");
print ("\n");

This is the same as

print "@file\n";
foreach $v (@file){
chomp($v);
printf ("%0.4x ",$v);
}

Here is where reading the FAQ entry I directed you to would have helped:

#!/usr/bin/perl

use strict;
use warnings;

my $input_fh;

if( @ARGV ) {
open $input_fh, '<', $ARGV[0]
or die "Cannot open $ARGV[0]: $!";
} else {
$input_fh = \*STDIN;
}

while( <$input_fh> ) {
print "Read: $_";
chomp;
printf "\t... converted to: %X\n", oct("0b$_");
}


Sinan
 
P

Paul Lalli

A. Sinan Unur said:
perldoc -q convert

Read all the text that is returned.

Also:

<URL:http://perldoc.perl.org/perlfaq4.ht...etween-numeric-representations/bases/radixes?>

I was indeed mistaken about perldoc.perl.org not having this FAQ (I
didn't realize that the snippet Jim posted was a sub-faq, and just
searched the page for the word 'binary'). For that I apologize.

However, under 5.6.1, `perldoc -q convert` returns only two FAQs:
How do I convert bits into ints? (The one I originally referred to)
How can I convert my shell script to perl?

"How do I convert between numeric representations/bases/radixes? is
apparently a newer addition to the FAQ.

Paul Lalli
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,173
Messages
2,570,939
Members
47,484
Latest member
JackRichard

Latest Threads

Top