Last active
April 19, 2024 19:34
-
-
Save maxux/786a9b8bf55fb0696f7e31b8fa3f6b9d to your computer and use it in GitHub Desktop.
Human readable size to bytes in C
This file contains hidden or 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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <inttypes.h> | |
#include <errno.h> | |
#include <string.h> | |
static char *human_readable_suffix = "kMGT"; | |
size_t *parse_human_readable(char *input, size_t *target) { | |
char *endp = input; | |
char *match = NULL; | |
size_t shift = 0; | |
errno = 0; | |
long double value = strtold(input, &endp); | |
if(errno || endp == input || value < 0) | |
return NULL; | |
if(!(match = strchr(human_readable_suffix, *endp))) | |
return NULL; | |
if(*match) | |
shift = (match - human_readable_suffix + 1) * 10; | |
*target = value * (1LU << shift); | |
return target; | |
} | |
int test(char *input, size_t expected) { | |
size_t value; | |
if(!parse_human_readable(input, &value)) { | |
if(expected == 0) | |
return printf("%-6s => error (expected)\n", input); | |
return printf("%-6s => error, expected: %lu\n", input, expected); | |
} | |
if(expected == value) | |
return printf("%-6s => %14lu [ok, expected: %lu]\n", input, value, expected); | |
return printf("%-6s => %14lu [error, expected: %lu]\n", input, value, expected); | |
} | |
int main(void) { | |
test("1337", 1337); | |
test("857.54", 857); | |
test("128k", 128 * 1024); | |
test("1.5k", 1536); | |
test("8M", 8 * 1024 * 1024); | |
test("0x55", 0x55); | |
test("0x55k", 0x55 * 1024); | |
test("1T", 1024 * 1024 * 1024 * 1024LU); | |
test("32.", 32); | |
test("-87", 0); | |
test("abcd", 0); | |
test("32x", 0); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ouput: