UPDATE
The code in my old answer isn't very efficient, but was very easy to understand and to implement. If you need to run the code on non-unix systems, or you can't access /dev/urandom
, and need a more performant code this is probably the best answer.
Please note that rand_buf()
I tried to code was worse then this function most of the times, so I decided to just copy-paste it.
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#if RAND_MAX == 0x7FFF
#define RAND_MAX_BITS 15
#elif RAND_MAX == 0x7FFFFFFF
#define RAND_MAX_BITS 31
#else
#error TBD code
#endif
#define byte unsigned char
#define MAX_BUS 32
//https://stackoverflow.com/a/50820616/9373031
//Queues leftover bits to optimize rand() 15 bits usage
void rand_buf(byte *dest, size_t size) {
int r;
int r_queue = 0;
int r_bit_count = 0;
for (size_t i = 0; i < size; i++) {
r = 0;
//printf("%3zu %2d %8x\n", i, r_bit_count, r_queue);
if (r_bit_count < 8) {
int need = 8 - r_bit_count;
r = r_queue << need;
r_queue = rand();
r ^= r_queue; // OK to flip bits already saved in `r`
r_queue >>= need;
r_bit_count = RAND_MAX_BITS - need;
} else {
r = r_queue;
r_queue >>= 8;
r_bit_count -= 8;
}
dest[i] = r;
}
}
int main(int argc, char *argv[]) {
srand(time(NULL));
byte * rbuf = malloc(MAX_BUS*2);
char buses[MAX_BUS][7];
rand_buf(rbuf, MAX_BUS*2);
for (int i = 0; i < MAX_BUS; i++) {
sprintf(buses[i], "37%02X%02X", rbuf[i*2], rbuf[i*2 + 1]);
//printf("%d = %s\n", i, buses[i]);
}
return 0;
}
rand_buf()
simply works by storing 7 leftover bits (rand()
returns at least 15 bits) and using "recycle" them later on.
OLD ANSWER
I would suggest using a better name for your function. Also you might want to end the arrays with \0
to create proper C strings. If you don't do it printf("%s")
will read the whole array
After that you have to choose a size for a new c-string array (char[MAX_BUS][6]
, where MAX_BUS
is the number of buses you will need to store).
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#define MAX_BUS 32
char rand_hex_char() { //returns a char not a char* (aka c-string)
//hexadecimal characters
char hex_characters[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
return hex_characters[rand()%16];
}
int main(int argc, char *argv[]) {
srand(time(NULL));
char buses[MAX_BUS][7];
for (int i = 0; i < MAX_BUS; i++) {
buses[i][0] = '3';
buses[i][1] = '7';
for (int j = 0; j < 4 /*rand chars*/; j++)
buses[i][j+2] = rand_hex_char();
buses[i][6] = 0;
printf("%d = %s\n", i, buses[i]);
}
printf("%s\n", buses[0]); //access the first bus
return 0;
}