For Programmers: Free Programming Magazines  


Home > Archive > PERL Miscellaneous > July 2005 > Converting a 4 byte field to integer.









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Converting a 4 byte field to integer.
Shashank Khanvilkar

2005-07-29, 5:03 pm

Hi,
All help is appreciated.
I have to read a binary file having a given structure (not important here).
One field that i need to read is a 4 byte field specifying some page
numeber.

If i want to display this page number, how can u do this?
The below fragment does not seem to work,

--SNIP--
read(IN, $buffer, 4); #IN is the fh for a file open in binary mode..
$page_number = ord($buffer);
print "[XXX] $page_number\n";
--SNIP--

For example, if $buffer contains the following four values,
0x74 0x29 0x00 0x00
then
print will print
[XXX] 116
which is dec(0x74)while I want dec(0x74|0x29|0x00|0x00);
(do not worry about the endianess at this point.)

Thanks
Shank

Paul Lalli

2005-07-29, 5:03 pm

Shashank Khanvilkar wrote:
> All help is appreciated.
> I have to read a binary file having a given structure (not important here).
> One field that i need to read is a 4 byte field specifying some page
> numeber.
>
> If i want to display this page number, how can u do this?
> The below fragment does not seem to work,


Just guessing here, but I bet you want to look into pack and/or unpack
perldoc -f pack
perldoc -f unpack
perldoc perlpacktut

> --SNIP--
> read(IN, $buffer, 4); #IN is the fh for a file open in binary mode..
> $page_number = ord($buffer);
> print "[XXX] $page_number\n";
> --SNIP--
>
> For example, if $buffer contains the following four values,
> 0x74 0x29 0x00 0x00
> then
> print will print
> [XXX] 116
> which is dec(0x74)


.... which is exactly what
perldoc -f ord
says would happen.

Paul Lalli

Sherm Pendley

2005-07-29, 5:04 pm

Shashank Khanvilkar <shashank@mia.ece.uic.edu> writes:

> The below fragment does not seem to work,
>
> --SNIP--
> read(IN, $buffer, 4); #IN is the fh for a file open in binary mode..
> $page_number = ord($buffer);


You need to get acquainted with pack() and unpack(). See:
perldoc -f pack
perldoc -f unpack
perldoc perlpacktut

In this case you'd use unpack(), like so:
my $page_number = unpack('L', $buffer);

sherm--

--
Cocoa programming in Perl: http://camelbones.sourceforge.net
Hire me! My resume: http://www.dot-app.org
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2009 codecomments.com