Assembly Language for Beginners

(Jeff_L) #1

1.23 Linear congruential generator.


Clear specific bit (known at compile stage)


Just applyANDoperation with the inverted value:


Listing 1.312: C/C++

value=value&(~0x40);


Listing 1.313: x86

AND REG, 0FFFFFFBFh


Listing 1.314: x64

AND REG, 0FFFFFFFFFFFFFFBFh


This is actually leaving all bits set except one.


ARM in ARM mode hasBICinstruction, which works like theNOT+ANDinstruction pair:


Listing 1.315: ARM (ARM mode)

BIC R0, R0, #0x40


Clear specific bit (specified at runtime)

Listing 1.316: C/C++

value=value&(~(1<<n));


Listing 1.317: x86

; CL=n
MOV REG, 1
SHL REG, CL
NOT REG
AND input_value, REG


1.22.7 Exercises



1.23 Linear congruential generator as pseudorandom number


generator


Perhaps, the linear congruential generator is the simplest possible way to generate random numbers.


It’s not in favour nowadays^156 , but it’s so simple (just one multiplication, one addition and AND operation),
that we can use it as an example.


#include <stdint.h>


// constants from the Numerical Recipes book
#define RNG_a 1664525
#define RNG_c 1013904223


static uint32_t rand_state;


(^156) Mersenne twister is better

Free download pdf