1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Hash Functions

  1. Mar 17, 2007 #1
    What exactly are hash functions and how do you use them to create a random string? What other ways are there to create random strings.
  2. jcsd
  3. Mar 17, 2007 #2

    One does not implement hash functions to produce a random string. Hash functions take a string as an argument and output a string of a smaller size which is a hash that represents the original string. An example of a hash function would be the famous DES.

    If you wish to produce a random string and not what a hash function does, you need a random byte generator. There are many methods of random generators. A common implementation of a random generator is to take the value of the time, and do a manipulation on it. Once you have a random byte generator, you can produce the number of bytes you want to produce a random string.
    Last edited: Mar 17, 2007
  4. Mar 18, 2007 #3
    How would you get the system time in c++ and use it to create a random string?
  5. Mar 18, 2007 #4


    User Avatar
    Gold Member

    I am not a C programmer but it seems to me you'd use the pseudo random number generator and seed it with the time:

    Code (Text):
    #include <ctime>    // For time()
    #include <cstdlib>  // For srand() and rand()
  6. Mar 19, 2007 #5
    Here is an example of a random string generator written in C. It generates a string of random capital letters.

    Code (Text):

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>

    main(int argc, char *argv[])
            if(argc < 2){
                    printf("USAGE: %s [Length of string]\n", argv[0]);
                    return 0;

            int length      = atoi(argv[1]);
            char *randstr   = malloc(length + 1);
            randstr[length] = '\0';

            time_t ltime = time(NULL);

            int i;
            for(i = 0; i < length; i++)
                    randstr[i] = (rand() % 26) + 65;

            printf("%s\n", randstr);
            return 0;

    Here is an example of the output:

    Code (Text):

    $ ./randstr
    USAGE: ./randstr [Length of string]
    $ ./randstr 20
    $ ./randstr 20
    $ ./randstr 20
    Last edited: Mar 19, 2007
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?

Similar Discussions: Hash Functions