バイト単位のサイズをログファイルや標準出力に出力する場合に分かりやすいように適切な単位(MB,GBなど)で表示するためのサンプルコードです。
#include <iostream>
struct SizeUnit {
size_t factor;
std::string unitStr;
};
const static SizeUnit NONE = { 1, "bytes" };
const static SizeUnit KILO = { 1024, "KB" };
const static SizeUnit MEGA = { KILO.factor * 1024, "MB" };
const static SizeUnit GIGA = { MEGA.factor * 1024, "GB" };
const static SizeUnit TERA = { GIGA.factor * 1024, "TB" };
const static int BUFSIZE = 100;
std::string format(const size_t sz, SizeUnit sizeUnit) {
char buf[BUFSIZE];
std::string fmt = sz % sizeUnit.factor == 0 ? "%.0f %s" : "%.1f %s";
std::snprintf(
buf, BUFSIZE, fmt.data(),
static_cast<double>(sz)/static_cast<double>(sizeUnit.factor),
sizeUnit.unitStr.data());
return std::string(buf);
}
std::string getFormattedNumber(const size_t sz){
if( sz > TERA.factor) {
return format(sz, TERA);
} else if( sz > GIGA.factor) {
return format(sz, GIGA);
} else if (sz > MEGA.factor) {
return format(sz, MEGA);
} else if (sz > KILO.factor) {
return format(sz, KILO);
} else {
return format(sz, NONE);
}
}
int main() {
std::cout
<< getFormattedNumber(234) << std::endl
<< getFormattedNumber(34543) << std::endl
<< getFormattedNumber(345387320) << std::endl
<< getFormattedNumber(275123793035) << std::endl
<< getFormattedNumber(31038852073273) << std::endl;
}
出力結果はこちら
$ ./GetformattedNumber
234 bytes
33.7 GB
329.4 MB
256.2 GB
28.2 TB