Skip to content

Instantly share code, notes, and snippets.

@maxux
Last active April 19, 2024 19:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxux/786a9b8bf55fb0696f7e31b8fa3f6b9d to your computer and use it in GitHub Desktop.
Save maxux/786a9b8bf55fb0696f7e31b8fa3f6b9d to your computer and use it in GitHub Desktop.
Human readable size to bytes in C
#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;
}
@maxux
Copy link
Author

maxux commented Dec 7, 2021

Ouput:

1337   =>           1337 [ok, expected: 1337]
857.54 =>            857 [ok, expected: 857]
128k   =>         131072 [ok, expected: 131072]
1.5k   =>           1536 [ok, expected: 1536]
8M     =>        8388608 [ok, expected: 8388608]
0x55   =>             85 [ok, expected: 85]
0x55k  =>          87040 [ok, expected: 87040]
1T     =>  1099511627776 [ok, expected: 1099511627776]
32.    =>             32 [ok, expected: 32]
-87    => error (expected)
abcd   => error (expected)
32x    => error (expected)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment