daveh71 has asked for the wisdom of the Perl Monks concerning the following question:

Perl newbie here
I'm reading a binary file like so
open (SOURCE, "<$FLWFILE"); binmode SOURCE, ":raw"; $rb = read(SOURCE, $byte, 1);
i think i'm reading it as unicode, and i really want it as hex. I think.
for example..
when $byte == 3 i really want 33 so i can do hex(33) to get 51.
when $byte == U i really want 55....
when $byte == C i really want 43...
in 2yr old language...how would I do this?
Thanks!!
david

Edit: chipmunk 2001-06-05

Replies are listed 'Best First'.
Re: unicode? conversion
by wog (Curate) on Jun 05, 2001 at 02:21 UTC
    You seem to really want to get the numerical value of the bytes in the file. (You are specifying there that you are not reading the file as unicode, just raw data.) That can be done with ord:

    my $value = ord $byte; my @values = map { ord } split //, $bytes;

    or with the "C" template using unpack.

    my $value = unpack "C", $byte; my @values = unpack "C*", $bytes;
    If you wanted the hexadecimal representation of the byte value you could use unpack using the "H" template.

    my $hex = unpack "H", $byte; my $hexstring = unpack "H*", $bytes; my @hex = unpack "H2" x length($bytes), $bytes;

    update: I might as well add a different way to do that last one (not involving x and therefore probably better):

    my @hex = ((unpack "H*", $bytes) =~ /(..)/g);
Re: unicode? conversion
by Vynce (Friar) on Jun 05, 2001 at 13:36 UTC
Re: unicode? conversion
by mattr (Curate) on Jun 05, 2001 at 12:53 UTC
    I may be missing something but man perlfunc tells me the binmode command only takes one argument, so what is ":raw" there for? Are you using a module which overrides the binmode function?

    Also, why are you using binmode? If you want to view your file in ascii and set position in file binmode does not seem appropriate. The file will be the same on disk whether it is on dos or unix. I would only use binmode if trying to read a line without specifying byte length to read.

    Also please check the usage of the read command in Perl. Otherwise the ord function does it in base 10, or see entries for hex and oct in the perl function manual. Here's mine.

    open (IN,"$filename") || die "Can't open $filename. $!\n"; read (IN,$buf,$numbytes,$startbyte) || die "Read error. $!\n"; close (IN);