Skip to content

Instantly share code, notes, and snippets.

@valkheim
Last active December 2, 2020 10:20
Show Gist options
  • Save valkheim/c182da33a1ef5a17c9f285911a652a56 to your computer and use it in GitHub Desktop.
Save valkheim/c182da33a1ef5a17c9f285911a652a56 to your computer and use it in GitHub Desktop.
Linear Congruential Generator
00000000004011b0 <my_srand>:
4011b0: 55 push rbp
4011b1: 48 89 e5 mov rbp,rsp
4011b4: 89 7d fc mov DWORD PTR [rbp-0x4],edi
4011b7: 8b 7d fc mov edi,DWORD PTR [rbp-0x4]
4011ba: 89 3c 25 3c 40 40 00 mov DWORD PTR ds:0x40403c,edi ; 0x40403c holds rand_state
4011c1: 5d pop rbp
4011c2: c3 ret
4011c3: 66 2e 0f 1f 84 00 00 nop WORD PTR cs:[rax+rax*1+0x0]
4011ca: 00 00 00
4011cd: 0f 1f 00 nop DWORD PTR [rax]
00000000004011d0 <my_rand>:
4011d0: 55 push rbp
4011d1: 48 89 e5 mov rbp,rsp
4011d4: 69 04 25 3c 40 40 00 imul eax,DWORD PTR ds:0x40403c,0x19660d ; rand_state * RNG_a
4011db: 0d 66 19 00
4011df: 89 04 25 3c 40 40 00 mov DWORD PTR ds:0x40403c,eax
4011e6: 8b 04 25 3c 40 40 00 mov eax,DWORD PTR ds:0x40403c
4011ed: 05 5f f3 6e 3c add eax,0x3c6ef35f ; rand_state + RNG_c
4011f2: 89 04 25 3c 40 40 00 mov DWORD PTR ds:0x40403c,eax
4011f9: 8b 04 25 3c 40 40 00 mov eax,DWORD PTR ds:0x40403c
401200: 25 ff 7f 00 00 and eax,0x7fff ; rand_state & SHRT_MAX (32767)
401205: 89 c0 mov eax,eax ; ORLY?
401207: 5d pop rbp
401208: c3 ret
401209: 0f 1f 80 00 00 00 00 nop DWORD PTR [rax+0x0]
#include <stdlib.h>
#include <stdint.h>
#include <limits.h>
#include <time.h>
#include <stdio.h>
#define RNG_a (1664525) // 0x19660d
#define RNG_c (1013904223) // 0x3c6ef35f
static uint32_t rand_state;
static void my_srand(uint32_t init)
{
rand_state = init;
}
static uint64_t my_rand()
{
rand_state = rand_state * RNG_a;
rand_state = rand_state + RNG_c;
return rand_state & SHRT_MAX;
}
int main()
{
my_srand((uint32_t)time(NULL));
for (int i = 0 ; i < 10 ; ++i)
printf("0x%lx\n", my_rand());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment