Skip to content

Instantly share code, notes, and snippets.

@erikdubbelboer
Last active December 10, 2015 08:08
Show Gist options
  • Save erikdubbelboer/4405902 to your computer and use it in GitHub Desktop.
Save erikdubbelboer/4405902 to your computer and use it in GitHub Desktop.
Format size in C
char* size(char* buffer, unsigned int length, unsigned int num) {
// floor(log(pow(2, 64)) / log(1024)) = 6
const char* unit[] = {
"B", "KB", "MB", "GB", "TB", "PB", "EB"
};
if (num == 0) {
snprintf(buffer, length, "0 %s", unit[0]);
} else {
unsigned int base = floor(log(num) / log(1024));
snprintf(buffer, length, "%.2f %s", num / pow(1024, base), unit[base]);
}
return buffer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment