Skip to content

Instantly share code, notes, and snippets.

@equalent
Forked from dgoguerra/human-size.c
Created July 23, 2019 09:00
Show Gist options
  • Save equalent/044ef11fedd9fee7fd4b32e21f7e44f4 to your computer and use it in GitHub Desktop.
Save equalent/044ef11fedd9fee7fd4b32e21f7e44f4 to your computer and use it in GitHub Desktop.
Format a quantity in bytes into a human readable string (C)
#include <stdio.h>
#include <stdlib.h> // atoll
#include <stdint.h> // uint64_t
#include <inttypes.h> // PRIu64
static const char *humanSize(uint64_t bytes)
{
char *suffix[] = {"B", "KB", "MB", "GB", "TB"};
char length = sizeof(suffix) / sizeof(suffix[0]);
int i = 0;
double dblBytes = bytes;
if (bytes > 1024) {
for (i = 0; (bytes / 1024) > 0 && i<length-1; i++, bytes /= 1024)
dblBytes = bytes / 1024.0;
}
static char output[200];
sprintf(output, "%.02lf %s", dblBytes, suffix[i]);
return output;
}
int main(int argc, char **argv)
{
if (argc == 1) {
fprintf(stderr, "Usage: %s <bytes>\n", *argv);
return 1;
}
uint64_t bytes = atoll(argv[1]);
printf("%" PRIu64 " Bytes: %s\n", bytes, humanSize(bytes));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment