Skip to content

Instantly share code, notes, and snippets.

@SatyaSnehith
Last active June 17, 2023 19:13
Show Gist options
  • Save SatyaSnehith/de7cbd7a4ace6a8c5e77b5e046b76f70 to your computer and use it in GitHub Desktop.
Save SatyaSnehith/de7cbd7a4ace6a8c5e77b5e046b76f70 to your computer and use it in GitHub Desktop.
Convert Bytes to KB, MB, GB, TB, PB, EB- C
// execution
// gcc size_converter.c -o size_converter && ./size_converter 512
#include<stdio.h>
#include<stdlib.h>
typedef unsigned long long ULL;
char *types[] = {"Bytes", "KB", "MB", "GB", "TB", "PB", "EB"};
int typesLen = (sizeof(types) / sizeof(types[0]));
ULL pow1024(int power) {
ULL result = 1024ULL;
for (int i = 2; i <= power; ++i) result *= 1024ULL;
return result;
}
// This function converts bytes to its category
// Example: converts 1024 bytes to 1 KB
//
// Parameters:
// str: converter value: maximum of 13 characters
// size: in bytes
//
void getSize(char* str, ULL size) {
int typeIndex = 0;
ULL bytesDiv = 1ULL;
for (int i = typesLen - 1; i >= 0; --i) {
bytesDiv = (ULL) pow1024(i);
if (size >= bytesDiv) {
typeIndex = i;
break;
}
}
sprintf(str, "%.2f %s", (double) size / bytesDiv, types[typeIndex]);
}
int main(int argc, char *argv[]) {
char str[13];
for (int i = 1; i < argc; ++i) {
ULL input = strtoull(argv[i], NULL, 10);
getSize(str, input);
printf("%llu -> %s \n", input, str);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment