[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 294
  • Last Modified:

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
Asked:
guidway
  • 2
  • 2
2 Solutions
 
AlexFMCommented:
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
 
guidwayAuthor 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
 
AlexFMCommented:
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
 
PaulCaswellCommented:
Hi guidway,

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

Paul
0
 
guidwayAuthor 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

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now