Guest User

Untitled

a guest
Jan 12th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.04 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdint.h>
  4. #include <time.h>
  5.  
  6. char* rand_str(const int length) {
  7.     const int n_len = 1 + length / sizeof(uint32_t);
  8.     uint32_t * const n = malloc(n_len);
  9.     const uint32_t mask_printable = 0x20202020; // make sure it's printable
  10.     const uint32_t mask_ascii     = 0x7F7F7F7F; // keep within ASCII range
  11.     // The shift is endianess-dependent. Right shift needed on little-endian.
  12.     const uint32_t last_mask      = length % 4 ? mask_ascii >> 8*(4 - (length % 4)) : 0;
  13.  
  14.     for(int i = 0; i < n_len; i++) {
  15.         n[i] = (uint32_t) ((int64_t) rand() - INT32_MIN);
  16.         n[i] |= mask_printable;
  17.         n[i] &= i == n_len - 1 ? last_mask : mask_ascii;
  18.     }
  19.  
  20.     return (char*) n;
  21. }
  22.  
  23. int main(int argc, char **argv) {
  24.     srand(time(NULL));
  25.     int len   = argc > 1 ? atoi(argv[1]) : 7;
  26.     int count = argc > 2 ? atoi(argv[2]) : 1;
  27.     char *s;
  28.     for(int i = 0; i < count; i++) {
  29.         s = rand_str(len);
  30.         printf("%s\n", s);
  31.         free(s);
  32.     }
  33.     return 0;
  34. }
Add Comment
Please, Sign In to add comment