Skip to content

Instantly share code, notes, and snippets.

@nyteshade
Created February 4, 2025 15:55
Show Gist options
  • Save nyteshade/dab9abec32c7dc39c65b77fe0a8061ba to your computer and use it in GitHub Desktop.
Save nyteshade/dab9abec32c7dc39c65b77fe0a8061ba to your computer and use it in GitHub Desktop.
Base 62 0-9a-zA-Z RandStr.c
#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;
}
@nyteshade
Copy link
Author

Universal macOS compilation

gcc -std=c99 -Wall -Wextra -arch x86_64 -o randstr-x86_64 randstr.c && \
gcc -std=c99 -Wall -Wextra -arch arm64 -o randstr-arm64 randstr.c && \
lipo -create -output randstr randstr-x86_64 randstr-arm64 && \
rm randstr-arm64 randstr-x86_64

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