Converting a 4 byte field to integer.

  • Thread starter Shashank Khanvilkar
  • Start date
S

Shashank Khanvilkar

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
 
P

Paul Lalli

Shashank said:
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
 
S

Sherm Pendley

Shashank Khanvilkar said:
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--
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top