我有一个整数,对应的文件大小以字节为单位。返回400的int大小为400字节,返回10400的int为10.4 KB。我想要做的是将类似10400的int转换为10.4,并且还可以区分10.4 KB,10.4 MB或10.4 GB。因为10400是10.4 KB,10400000是10.4 MB,10400000000是10.4 GB。有人有解决方案吗?
答案 0 :(得分:2)
您可以使用以下方式执行此操作:
void pretty_bytes(char* buf, uint bytes)
{
const char* suffixes[7];
suffixes[0] = "B";
suffixes[1] = "KB";
suffixes[2] = "MB";
suffixes[3] = "GB";
suffixes[4] = "TB";
suffixes[5] = "PB";
suffixes[6] = "EB";
uint s = 0; // which suffix to use
double count = bytes;
while (count >= 1024 && s < 7)
{
s++;
count /= 1024;
}
if (count - floor(count) == 0.0)
sprintf(buf, "%d %s", (int)count, suffixes[s]);
else
sprintf(buf, "%.1f %s", count, suffixes[s]);
}
如果您不想使用缓冲区:
static const char *humanSize(uint64_t bytes)
{
char *suffix[] = {"B", "KB", "MB", "GB", "TB"};
char length = sizeof(suffix) / sizeof(suffix[0]);
int i = 0;
double dblBytes = bytes;
if (bytes > 1024) {
for (i = 0; (bytes / 1024) > 0 && i<length-1; i++, bytes /= 1024)
dblBytes = bytes / 1024.0;
}
static char output[200];
sprintf(output, "%.02lf %s", dblBytes, suffix[i]);
return output;
}