Calculation returning wrong value

Programming, for all ages and all languages.
Post Reply
User avatar
DerekDouglas
Posts: 16
Joined: Thu Sep 27, 2007 8:05 pm
Location: Ontario, Canada
Contact:

Calculation returning wrong value

Post by DerekDouglas »

Hi guys,
I'm attempting to calculate the partition size from the MBR record of my drive. I have parsed all the information and even built a proper 32-bit value of the number of blocks in the partition. I am then multiplying the number of blocks by 512 bytes.

0x12a18a82 hex is 312576642 decimal. I calculate that by 512 using the calculator and get 160,039,240,704 which is correct. I have a 160GB partition. However when I try to calculate this into a long long (8 byte size in Windows) using C and get 1,125,450,752. Any reason why it is doing this?

Code: Select all

    long long tempPartSize = 0;
    unsigned int numBlocks = 0;

    /* Calculate partition size from number of blocks */
    numBlocks = Concat32BitLE(partBuffer[12], partBuffer[13], partBuffer[14], partBuffer[15]);
    
    printf("Number of blocks (hex): 0x%08x\n", numBlocks);
    printf("Number of blocks (dec): %d\n", numBlocks);
    
    tempPartSize = (numBlocks * 512);

    printf("Partition size: %lld\n", tempPartSize);
This outputs:
Number of blocks (hex): 0x12a18a82
Number of blocks (dec): 312576642
Partition size: 1125450752

Any suggestions?
User avatar
bewing
Member
Member
Posts: 1401
Joined: Wed Feb 07, 2007 1:45 pm
Location: Eugene, OR, US

Re: Calculation returning wrong value

Post by bewing »

It is doing this because the result is not cast into a long long until the calculation hits the = sign. That is, the numBlocks * 512 is calculated entirely as an unsigned int. Which truncates to 32 bits.

To fix it, all you need to do is cast it: tempPartSize = ((long long) numBlocks) * 512;
User avatar
DerekDouglas
Posts: 16
Joined: Thu Sep 27, 2007 8:05 pm
Location: Ontario, Canada
Contact:

Re: Calculation returning wrong value

Post by DerekDouglas »

bewing wrote:It is doing this because the result is not cast into a long long until the calculation hits the = sign. That is, the numBlocks * 512 is calculated entirely as an unsigned int. Which truncates to 32 bits.

To fix it, all you need to do is cast it: tempPartSize = ((long long) numBlocks) * 512;
Thanks! I had tried casting numBlocks to a long long, but I hadn't put the parenthesis around the cast AND numBlocks; the parenthesis around (numBlocks *512) was because I was doing a division before to show the value in GiB.

Works great now, thanks again Bewing. :)
Post Reply