cpp

All posts tagged cpp

I spend a lot of time write and debugging command line scripts and programs. As much as I like looking at large numbers (millions, billions, trillions, etc) it can be difficult to read a big number and quickly parse how large it is, i.e. “is that 12 megabytes or 1.2 gigabytes?”.

A long time ago I wrote a small function that does pretty printing of a number of bytes. It can handle from bytes to exabytes, and properly handles integer numbers of a unit by printing it as an integer instead of float. Should be easy enough to adjust to your specific needs or style desires.

// Prints to the provided buffer a nice number of bytes (KB, MB, GB, etc)
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]);
}