Advertisement
linuxlizard

Random hex string in C++

Mar 17th, 2015
344
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.08 KB | None | 0 0
  1. /* Generate a random hexidecimal string of large number of nibbles.
  2.  * (Created because needed a 204-bit integer.)
  3.  *
  4.  * davep 17-Mar-2015
  5.  */
  6.  
  7. #include <iostream>
  8. #include <string>
  9. #include <random>
  10. #include <algorithm>
  11. #include <chrono>
  12.  
  13. using namespace std;
  14.  
  15. /* With assistance from  
  16.  * https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c
  17.  * http://www.cplusplus.com/reference/random/linear_congruential_engine/linear_congruential_engine/
  18.  */
  19. string random_hex_string( size_t length )
  20. {
  21.     unsigned seed1 = chrono::system_clock::now().time_since_epoch().count();
  22.     string charset { "0123456789abcdef" };
  23.     auto gen = bind(uniform_int_distribution<unsigned int>{0,charset.size()-1},
  24.                     default_random_engine{seed1});
  25.  
  26.     auto randchar = [&charset,&gen]() -> char
  27.     {
  28.         return charset.at(gen());
  29.     };
  30.  
  31.     string str(length,0);
  32.     generate_n( str.begin(), str.size(), randchar );
  33.     return str;
  34. }
  35.  
  36. int main()
  37. {  
  38.     string str = random_hex_string(51);
  39.     cout << str << '\n';
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement