RodrigoDornelles / 3bc-lang

Low-level language, tiny virtual machine, minimal runtime, intermediate representation, embeddable, easy for beginners. (Friendly Punched cards)
https://3bc-lang.org
GNU General Public License v3.0
232 stars 25 forks source link

add cpu mode for random number generate #346

Open RodrigoDornelles opened 1 year ago

RodrigoDornelles commented 1 year ago

something that is always convenient has a random number generator, can be implemented from scratch, to be similar on all platforms that run the virtual machine.

uint16_t prng16(uint16_t *seed1, uint16_t *seed2) {
    uint16_t hl = *seed1;
    uint8_t b = (hl >> 8) & 0xFF;
    uint8_t c = hl & 0xFF;

    hl <<= 1;
    if (c & 0x80) {
        hl += 1;
    }
    hl += (b << 8) | c;

    *seed1 = hl;

    hl = *seed2;
    hl <<= 1;

    uint8_t a = 0;
    a &= 0x2D; // This corresponds to and %00101101
    a ^= (uint8_t)hl;
    hl = (hl & 0xFF00) | a;

    *seed2 = hl;

    hl += (b << 8) | c;

    return hl;
}

Z80 Assembly

 prng16:
;Inputs:
;   (seed1) contains a 16-bit seed value
;   (seed2) contains a NON-ZERO 16-bit seed value
;Outputs:
;   HL is the result
;   BC is the result of the LCG, so not that great of quality
;   DE is preserved
;Destroys:
;   AF
;cycle: 4,294,901,760 (almost 4.3 billion)
;160cc
;26 bytes
    ld hl,(seed1)
    ld b,h
    ld c,l
    add hl,hl
    add hl,hl
    inc l
    add hl,bc
    ld (seed1),hl
    ld hl,(seed2)
    add hl,hl
    sbc a,a
    and %00101101
    xor l
    ld l,a
    ld (seed2),hl
    add hl,bc
    ret