Last active
December 10, 2015 08:08
-
-
Save erikdubbelboer/4405902 to your computer and use it in GitHub Desktop.
Format size in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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