C++ Utility function for converting bytes to higher units


Sometimes you need a handy function to convert number of bytes to a human readable size. I wrote a C++ version but found better logic on StackOverflow but implemented in C so decided to implement a similar function in C++.

/**
*Function to convert number of bytes to higher units.
*Inspired from C version of source from:
*http://stackoverflow.com/questions/3898840/converting-a-number-of-bytes-into-a-file-size-in-c
*/

#include
#include
#include
#include
#include

#define LIST_SZ(x) (sizeof(x)/sizeof(*(x)))

static const char *units[] = { "TiB", "GiB", "MiB", "KiB", "B" };
static const unsigned long tebibytes = 1024ULL * 1024ULL * 1024ULL * 1024ULL;

std::string
HumanReadableSize(unsigned long bytes)
{
std::stringstream result;
unsigned long multiplier = tebibytes;

for (int i = 0; i < LIST_SZ(units); i++, multiplier /= 1024)
{
if (bytes < multiplier)
continue;
if (bytes % multiplier == 0)
result << (bytes / multiplier) << " " << units[i] << std::fixed;
else
result << std::setprecision(4) << ((float) bytes / multiplier) << " " << units[i];
return result.str();
}
result << "0";
return result.str();
}

//Unit Test function
int main(void)
{
unsigned long list[] =
{
0, 1, 2, 34, 900, 1023, 1024, 1025, 2048, 1024 * 1024,
1024 * 1024 * 1024 + 1024 * 1024 * 400
};

for (int i = 0; i < LIST_SZ(list); i++)
{
std::cout << HumanReadableSize(list[i]);
std::cout << std::endl;
}
std::cout << HumanReadableSize(2966141478);
return 0;
}