x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 295

# file size question

I'm attempting to learn how to read file formats and am having some trouble figuring out what is going on here. The format description states:

"The value for file length is the total length of the file in 16-bit words (including the fifty
16-bit words that make up the header)."

This is how the file length is stored in the header:
Byte 24    File Length    Integer    Big Endian

I read the value from byte 24 as 4 bytes (integer size) in Big endian and I get the value 10106 which I thought would be valid, however I found someone else that wrote a library on the internet (w/ source code) that works and I'm trying to understand what they are doing as they get the value 20212 when I run it. Their code is:

psSHP->nFileSize = (pabyBuf[24] * 256 * 256 * 256
+ pabyBuf[25] * 256 * 256
+ pabyBuf[26] * 256
+ pabyBuf[27]) * 2;

I don't understand why they are multiplying by 256 to figure up the file size? And why is the right-most value multiplied by 2? thanks for any help!
0
guidway
• 2
• 2
2 Solutions

Commented:
2 is because value in 16-bit words is converted to bytes.
Other is binary arithmetic, like this decomal sample:
132 = 1 * 10^2 + 3 * 10 + 2
0

Author Commented:
So if it is being converted to bytes, couldn't you just read all 4 bytes (as I did) as an integer for filesize and then multiply by 2 to get the number of bytes or is that not always going to give the same result?

I guess I'm trying to figure out why they are breaking each value down instead of reading all 4 bytes at once. (I'm actually writing this in C#, but I posted here since it was C code).

I thought I was making some progress understanding this, but its taking a while to sink in fully.
0

Commented:
This is done because value is kept in Big Endian format, and code runs on Little Endian computer. Simple conversion of 4 bytes gives incorrect result.
0

Commented:
Hi guidway,

Notice that x * 256 == x << 8 so 'pabyBuf[24] * 256 * 256 * 256' is equivalent to 'pabyBuf[24] << (8+8+8)'.

Paul
0

Author Commented:
that makes sense. I never realized shifting by 8 is the same as multiplying by 256. I see I still have a lot to learn. Thanks to both of you, that helps a lot. Increasing to 400 and splitting.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.