Anybody knows the exact implementation for Borland C++ rand() function?
I tried to the following but the results are not similar to ones I got with real TurboC 4.5. Naturally I tried the code with different variations but with no success.
unsigned int seed = 1;
void srand(unsigned int newSeed) {
    seed = newSeed;
}
#define MAX_RAND 0x7FFF;
unsigned int lrand()
{
    int a = 22695477;
    int c = 1;
    seed = (a * seed + c);
    return seed;
}
unsigned int rand() {
     return (lrand() >> 16) & MAX_RAND;
}
http://en.wikipedia.org/wiki/Linear_congruential_generator
Here's what I've got, not sure if your version of the compiler has the same implementation of rand() and srand():
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
/*
  Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland
  srand:
    push      ebp
    mov       ebp, esp
    mov       eax, [ebp + 8]
    mov       [seed], eax
    xor       edx, edx
    mov       [seed + 4], edx ; seed high ?
    call      rand
    pop       ebp
    ret
  rand:
    imul      eax, dword [seed], 015A4E35H
    inc       eax
    mov       [seed], eax
    shr       eax, 10H
    and       eax, 7FFFH
    ret
  seed    dd  015A4E36H, 0
*/
unsigned int myseed = 0x015A4E36;
int myrand(void)
{
  unsigned int t = myseed * 0x015A4E35 + 1;
  myseed = t;
  return (int)(t >> 16) & 0x7FFF;
}
void mysrand(unsigned int seed)
{
  myseed = seed;
  myrand();
}
int main(void)
{
  unsigned t = time(NULL);
  printf("%d %d\n", rand(), myrand());
  printf("%d %d\n", rand(), myrand());
  printf("%d %d\n", rand(), myrand());
  printf("%d %d\n", rand(), myrand());
  srand(t);
  mysrand(t);
  printf("%d %d\n", rand(), myrand());
  printf("%d %d\n", rand(), myrand());
  printf("%d %d\n", rand(), myrand());
  printf("%d %d\n", rand(), myrand());
  return 0;
}
Output:
130 130
10982 10982
1090 1090
11656 11656
23367 23367
13875 13875
12650 12650
13257 13257
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With