Created
February 4, 2025 15:55
-
-
Save nyteshade/dab9abec32c7dc39c65b77fe0a8061ba to your computer and use it in GitHub Desktop.
Base 62 0-9a-zA-Z RandStr.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 <time.h> | |
#include <string.h> | |
#include <math.h> | |
#include <ctype.h> | |
int wal_stricmp(const char *a, const char *b) { | |
int ca, cb; | |
do { | |
ca = *((unsigned char *) a++); | |
cb = *((unsigned char *) b++); | |
ca = tolower(toupper(ca)); | |
cb = tolower(toupper(cb)); | |
} while (ca == cb && ca != '\0'); | |
return ca - cb; | |
} | |
void generate_random_string(char *str, size_t len) { | |
static const char charset[] = | |
"0123456789" | |
"abcdefghijklmnopqrstuvwxyz" | |
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"; | |
static int limit = RAND_MAX - (RAND_MAX % strlen(charset)); | |
for (size_t i = 0; i < len; i++) { | |
int index = (int)((rand() * rand() + i) % strlen(charset)); | |
str[i] = charset[index]; | |
rand(); | |
} | |
} | |
int main(int argc, char **argv) { | |
size_t len = 12; | |
size_t times = 1; | |
char *random_str = NULL; | |
unsigned int i = 0; | |
unsigned int cur_time = 0; | |
if (argc == 2 && !wal_stricmp(argv[1], "help")) { | |
printf("%s\n", | |
"Usage: \x1b[36mrandstr\x1b[39m <\x1b[33mcount\x1b[39m> <\x1b[33mrepeat\x1b[39m>\n" | |
"where\n" | |
" \x1b[33mcount\x1b[39m - number of digits; defaults to 12\n" | |
" \x1b[33mrepeat\x1b[39m - repeat number of times; defaults to 1\n" | |
); | |
return 0; | |
} | |
if (argc > 1) { | |
int requested_len = atoi(argv[1]); | |
if (requested_len < 1) len = 1; | |
else if (requested_len > 100) len = 100; | |
else len = requested_len; | |
} | |
if (argc > 2) { | |
int requested_repeats = atoi(argv[2]); | |
if (requested_repeats < 1) times = 1; | |
else if (requested_repeats > 100) times = 100; | |
else times = requested_repeats; | |
} | |
random_str = (char*)calloc(len + 1, sizeof(char)); | |
if (!random_str) { | |
printf("Could not allocate memory for string\n"); | |
return 1; | |
} | |
cur_time = (unsigned int)time(NULL); | |
srand(cur_time); | |
for (i = 0; i < times; i++) { | |
generate_random_string(random_str, len); | |
printf("%s%s", i > 0 ? " " : "", random_str); | |
} | |
printf("\n"); | |
if (random_str) | |
free(random_str); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Universal macOS compilation