Page 1 of 1

Calculation returning wrong value

Posted: Sat Feb 21, 2009 11:30 pm
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?

Re: Calculation returning wrong value

Posted: Sun Feb 22, 2009 7:12 am
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;

Re: Calculation returning wrong value

Posted: Sun Feb 22, 2009 8:27 am
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. :)