Thread: Playing with random numbers

  1. #1
    Registered User
    Join Date
    Mar 2013
    Posts
    18

    Playing with random numbers

    Hi everyone I am hoping someone can point out the error in the following code fragment (please excuse the sloppy coding I am just starting to learn c).
    First rotation through the for loop correctly returns the hex value however second time around it does not?

    First myRand = 4D should result in FFFFFFFF and does
    Second myRand = 15FC should result in FFFFFFFA doesn't work?

    Code:
     srand(length);  // seed rand generator
    
        for (i = 0; i < length; ++i) {
            myRand =  rand();   // get random number
            myDivMod = myRand % length;
            // myRand = length / 2;
            myRand = myRand / length;  
            myRand = myRand * -1;               
            myRand = myRand + myDivMod;
    
    //I would like to change string1 directly here instead of using a string2 can I do that?
    
            j = string1[i]; 
            j += myRand;
            string2[i] = j;
        }
    Thanks for taking the time to read this and any suggestions are MOST welcome.

    cheers

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Post a complete code we can copy/paste/run to see what you're seeing.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Mar 2013
    Posts
    18
    Quote Originally Posted by Salem View Post
    Post a complete code we can copy/paste/run to see what you're seeing.
    Object is to change an inputted string characters as per the massaged values of the random number
    I want to use the ist byte of hex value eg. FA in hex value FFFFFFFA
    and add that to the value of the character in the input string


    Code:
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    
    
    int main()
    {
        char string1[30], string2[30], myHexBuf[50],j;
        int i, length, bufsize, myBuf, myDivMod, myDivAdd, myDivStrlen;
        unsigned int myRand; //myHexBuf;  //, myRand;
    
    
    
    
        printf("Enter String\n");
    
    
        scanf("%s",string1);
    
    
        length = strlen(string1);
        
        bufsize = length * 4;
    
    
        myBuf = (malloc(bufsize));  // allocate buffer size of strlen chars
        string * 4 for the hex values
    
    
        srand(length);  // seed rand generator
    
    
        for (i = 0; i < length; ++i) {
            myRand =  rand();   // get random number
            myDivMod = myRand % length; // - length / 2;  // get mod of random number
             myRand = myRand / length;  //  should equal 6 with 4D random
            myRand = myRand * -1;    // negate mRand by * -1
             myRand = myRand + myDivMod;
            
        //j = string1[i];
            //j += myRand;
            //string2[i] = j;
        }
    
    
    
    
        return 0;
    }

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    That makes no sense.
    FA?
    4D?
    Your current random number generator might start off like that, but everyone else sees different things.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main()
    {
      char string1[30] = "hello"; 
      int length, myDivMod;
      unsigned int myRand;
    
      length = strlen(string1);
    
      srand(length);                // seed rand generator
    
      for (int i = 0; i < length; ++i) {
        myRand = rand();            // get random number
        printf("R1=%10u(%10x) ", myRand, myRand);
        myDivMod = myRand % length; // - length / 2;  // get mod of random number
        myRand = myRand / length;   //  should equal 6 with 4D random
        printf("R2=%10u(%10x) ", myRand, myRand);
        myRand = myRand * -1;       // negate mRand by * -1
        myRand = myRand + myDivMod;
        printf("R3=%10u(%10x)\n", myRand, myRand);
      }
    
      return 0;
    }
    
    
    $ ./a.out 
    R1= 590011675(  232add1b) R2= 118002335(   708929f) R3=4176964961(  f8f76d61)
    R1=  99788765(   5f2a7dd) R2=  19957753(   13087f9) R3=4275009543(  fecf7807)
    R1=2131925610(  7f129a6a) R2= 426385122(  196a1ee2) R3=3868582174(  e695e11e)
    R1= 171864072(   a3e7008) R2=  34372814(   20c7cce) R3=4260594484(  fdf38334)
    R1= 317159276(  12e7776c) R2=  63431855(   3c7e4af) R3=4231535442(  fc381b52)
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Registered User
    Join Date
    Mar 2013
    Posts
    18
    Thanks for the reply but I am now definitely lost I am using Code Blocks and the length of my string is 12 characters

    1st return from rand() returns 77 or 0x4D
    2nd return from rand() returns 5628 or 0x15FC
    3rd return from rand() returns 6232 or 0x1858
    4th return from rand() returns 29052 or 0x717C

    is the rand function machine specific ?

    These are the same values which are returned under IDA

    cheers

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by ice_cracked
    is the rand function machine specific ?
    The rand function is implementation specific.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  7. #7
    Registered User
    Join Date
    Mar 2013
    Posts
    18
    So should the rand function seeded with the same value return the same value on any machine it is used on ?

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    No, but the same seed must produce the same pseudorandom sequence for the same implementation of the standard library. However, standard library implementations can differ, hence across different machines, or even the same machine with the same program compiled against different standard library implementations, the same seed could result in different pseudorandom sequences.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Registered User
    Join Date
    Dec 2017
    Posts
    1,626
    Maybe you meant something more like this.
    Code:
    #include <ctype.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <time.h>
     
    int main() {
        const int NumLetters = 26;
        char s[] = "Hello World";
        int len = strlen(s);
     
        srand(time(NULL));
     
        for (int i = 0; i < len; ++i) {
            printf("[%c]", s[i]);
            if (isalpha(s[i])) { // don't modify non-alphabetic chars
                int r = rand() % NumLetters;
                printf(" + %2d", r);
                char base = islower(s[i]) ? 'a' : 'A';
                s[i] = (s[i] - base + r) % NumLetters + base;
                printf(" = [%c]", s[i]);
            }
            putchar('\n');
        }
        
        printf("\n%s\n", s);
     
        return 0;
    }
    Code:
    [H] + 20 = [B]
    [e] + 15 = [t]
    [l] + 25 = [k]
    [l] + 18 = [d]
    [o] + 15 = [d]
    [ ]
    [W] +  6 = [C]
    [o] +  3 = [r]
    [r] + 20 = [l]
    [l] +  2 = [n]
    [d] +  3 = [g]
     
    Btkdd Crlng
    A little inaccuracy saves tons of explanation. - H.H. Munro

  10. #10
    Registered User
    Join Date
    Mar 2013
    Posts
    18
    Thanks for your time and reply I must admit I don't follow half of what you are saying :-(
    On my machine using "First Second" as an input string which has 12 characters the 12 is then used to seed the rand call.
    The first rand call returns 0x4D.
    That value is divided by the 12 characters entered the result is 6 into the EAX register and the modulo which is 5 is saved EDX.
    The strlen value in this case 12 which is in EAX is divided by 2 by sar 1 so it is now 6.
    The value is EAX is then negated by multiplying it by -1 which results in FFFFFFFA in the EAX register.
    The mod value contained in the EDX register is added to EAX which now becomes FFFFFFFF.
    The last FF byte is then added to the first character of the string entered which just deducts 1 from its value so the "F"
    character 0x46 or decimal 70 becomes ox45 or decimal 69 so is changed to an "E".
    The next rand call returns 0x15FC and the process above eventually ends in FFFFFFFA in the EAX register which
    when added to the second character of the string entered an "i" subtracts 6 from it's value
    "i" becomes "c".
    The third call to rand returns 0x1858 and the loop continues changing all of the entered characters in the input string
    by the values after the calculations on the rand number returned.

    BUT if the rand value returned is only correct for my machine I can't do what I am trying to do.

  11. #11
    Registered User
    Join Date
    Dec 2017
    Posts
    1,626
    This sounds totally idiotic.
    You really don't seem to know what you're talking about (and I know assembly quite well).
    Forget I said anything.
    A little inaccuracy saves tons of explanation. - H.H. Munro

  12. #12
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    rand() is a pseudo random number generator. It isn't really random, just appears to be. It depends on the initial value seeded to the algorithm. If this value is 12, rand() will always give you the same sequence. Run this program multiple times to see:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main( void )
    {
      int i;
    
      srand( 12 );
      for ( i = 0; i < 10; i++ )
        printf( "%d ", rand() );
      putchar( '\n' );
    }
    Code:
    $ cat test.c
    #include <stdio.h>
    #include <stdlib.h>
    
    int main( void )
    {
      int i;
    
      srand( 12 );
      for ( i = 0; i < 10; i++ )
        printf( "%d ", rand() );
      putchar( '\n' );
    }
    $ cc -o test test.c
    $ ./test
    1687063760 945274514 247215794 1768547008 1478315323 279012855 668221829 1109214873 1378701697 1054489464 
    $ ./test
    1687063760 945274514 247215794 1768547008 1478315323 279012855 668221829 1109214873 1378701697 1054489464 
    $ ./test
    1687063760 945274514 247215794 1768547008 1478315323 279012855 668221829 1109214873 1378701697 1054489464

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Is C playing tricks with me? Random Seg faults
    By tmac619619 in forum C Programming
    Replies: 1
    Last Post: 09-15-2015, 12:53 AM
  2. Random numbers not random?
    By yacek in forum C Programming
    Replies: 6
    Last Post: 10-08-2010, 06:57 PM
  3. random numbers
    By Saimadhav in forum C++ Programming
    Replies: 7
    Last Post: 07-29-2008, 08:53 AM
  4. Replies: 4
    Last Post: 11-16-2004, 07:29 AM
  5. How can I get random numbers from 60 to 100
    By Unregistered in forum C Programming
    Replies: 6
    Last Post: 06-26-2002, 07:43 PM

Tags for this Thread