开发者

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.

i.e. 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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜