Skip to content

Instantly share code, notes, and snippets.

@saxbophone
Last active March 22, 2019 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saxbophone/7d6bc61d89486f7a41e8d5d3d696f9eb to your computer and use it in GitHub Desktop.
Save saxbophone/7d6bc61d89486f7a41e8d5d3d696f9eb to your computer and use it in GitHub Desktop.
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
typedef enum BinaryPrefix {
BINARY_PREFIX_NONE = 0, // × 1024°
BINARY_PREFIX_KIBI, // × 1024¹
BINARY_PREFIX_MEBI, // × 1024²
BINARY_PREFIX_GIBI, // × 1024³
BINARY_PREFIX_TEBI, // × 1024⁴
BINARY_PREFIX_PEBI, // × 1024⁵
BINARY_PREFIX_EXBI, // × 1024⁶
BINARY_PREFIX_ZEBI, // × 1024⁷
BINARY_PREFIX_YOBI, // × 1024⁸
} BinaryPrefix;
typedef struct DataUnit {
double units;
BinaryPrefix prefix;
} DataUnit;
DataUnit bytes_to_prefixed_data_units(size_t bytes) {
DataUnit result = {
.units = bytes,
.prefix = BINARY_PREFIX_NONE,
};
while (result.units >= 1024.0 && result.prefix < BINARY_PREFIX_YOBI) {
result.units /= 1024.0;
result.prefix++;
}
return result;
}
const char* unit_prefix(BinaryPrefix prefix) {
switch(prefix) {
case BINARY_PREFIX_NONE:
return "B";
case BINARY_PREFIX_KIBI:
return "KiB";
case BINARY_PREFIX_MEBI:
return "MiB";
case BINARY_PREFIX_GIBI:
return "GiB";
case BINARY_PREFIX_TEBI:
return "TiB";
case BINARY_PREFIX_PEBI:
return "PiB";
case BINARY_PREFIX_EXBI:
return "EiB";
case BINARY_PREFIX_ZEBI:
return "ZiB";
case BINARY_PREFIX_YOBI:
return "YiB";
default:
return "<unknown unit>";
}
}
void data_unit_to_string(
DataUnit data_unit,
char* output_string,
size_t length
) {
snprintf(
output_string,
length,
"%f%s",
data_unit.units,
unit_prefix(data_unit.prefix)
);
}
void bytes_to_binary_prefix_string(
size_t bytes,
char* output_string,
size_t length
) {
data_unit_to_string(
bytes_to_prefixed_data_units(bytes),
output_string,
length
);
}
int main(void) {
char buffer[256];
// z = x^y
size_t x = 15;
size_t y = 5;
size_t z = 1;
for (size_t i = 0; i < y; i++) {
z *= x;
}
bytes_to_binary_prefix_string(z, buffer, sizeof(buffer));
printf("%s (%zu)\n", buffer, z);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment