简体   繁体   中英

C++ long long manipulation

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.

ie 1234567899878Bytes = 1177375.698MiB ??

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM