views:

100

answers:

1

Given 2 32bit ints iMSB and iLSB

int iMSB = 12345678; // Most Significant Bits of file size in Bytes
int iLSB = 87654321; // Least Significant Bits of file size in Bytes

the long long form would be...

// Always positive so use 31 bts
long long full_size =  ((long long)iMSB << 31);
          full_size += (long long)(iLSB);

Now..

I don't need that much precision (that exact number of bytes), so, how can I convert the file size to MiBytes to 3 decimal places and convert to a string...

tried this...

long double file_size_megs = file_size_bytes / (1024 * 1024);
char strNumber[20];
sprintf(strNumber, "%ld", file_size_megs);

... but dosen't seem to work.

i.e. 1234567899878Bytes = 1177375.698MiB ??

+8  A: 

You misunderstand how the operation works. Your computation should be:

// Always use 32 bits
long long full_size = ((long long)iMSB << 32); 
          full_size += (unsigned long long)(iLSB);

However, the combination of 12345678, 87654321 is not 1234567887654321; it's 53024283344601009.

Then when you do

long double file_size_megs = file_size_bytes / (1024 * 1024);
char strNumber[20];
sprintf(strNumber, "%ld", file_size_megs);

You are taking a long double (which is a floating point format) and printing it with %ld which is an integer format. What you meant was:

long long file_size_megs = file_size_bytes / (1024 * 1024);
char strNumber[20];
sprintf(strNumber, "%lld", file_size_megs);

An alternative is to compute just the filesize in MB:

long long file_size_megs = ((long long)iMSB << (32 - 20)) + ((unsigned)iLSB >> 20);
Gabe
+1 for the bravery to answer to a such b0rked question. The values being signed may pose a difficulty, though. I would recommend simply making all integer variables unsigned to avoid such issues.
Tronic
this sprintfs the long long as a long, use %lld.
nos
Since this is marked C++, one should be using streams instead of sprintf anyway (and avoid those nasty formatting string bugs).
Tronic
I made the LSB unsigned and put in the %lld. Thanks Tronic and nos
Gabe
> @gabe However, the combination of 12345678, 87654321 is not 1234567887654321; it's 53024283344601009.yes I realise that.
Krakkos
Sorry, Krakkos, it wasn't clear what you were expecting based on your example.
Gabe
@tronic - the question may be b0rked... but thats one of the joys of using crappy third party libraries with nasty API calls.
Krakkos