Generating Number and putting in Byte Array

Viewed 54

The idea is to generate non cryptographic numbers using a Linear Congruential Generator. It has an internal state consisting of a number xi initially set to x0 = seed. I need to take out the output bytes of given length from this generator.

print("The formula is: X(k+1) = a * Xk + c mod m")
seed_num = int(input("Enter seed number: "))
multiplier = int(input("Enter the multiplier(a): "))
increment = int(input("Enter the increment(c): "))
modulus = int(input("Enter the modulus (m): "))
unit = int(input("How many random numbers would you like to generate?\nInput: "))


def lcg():
    num_base = seed_num
    for i in range(unit, 0, -1):
        rd = (multiplier * num_base + increment) % modulus
        print(rd)
        num_base = rd


lcg()  

I need to get a byte array from what is being generated using this LCG code. I need the output bytes sequentially starting from the byte generated in the first iteration and ending with the byte generated in the last iteration.

2 Answers

I think you are looking for bytearray() function.

lcg = [16, 25, 37, 53, 1, 5, 47, 48, 31, 45, 27, 3, 26, 20, 12, 38, 36, 15, 42, 23, 16, 25, 37, 53, 1, 5, 47, 48, 31, 45, 27, 3, 26, 20, 12, 38, 36, 15, 42, 23, 16, 25, 37, 53, 1, 5, 47, 48, 31, 45, 27, 3, 26, 20, 12, 38, 36, 15]
bytearray(lcg) # bytearray(b'\x10\x19%5\x01\x05/0\x1f-\x1b\x03\x1a\x14\x0c&$\x0f*\x17\x10\x19%5\x01\x05/0\x1f-\x1b\x03\x1a\x14\x0c&$\x0f*\x17\x10\x19%5\x01\x05/0\x1f-\x1b\x03\x1a\x14\x0c&$\x0f')

If you want to just convert a number to byte, you can also do this:

bytes([x])

where x is an integer from 0 to 255.

If this is not what you are looking for, please add an example of what you want to do.

As the bytes are created in the lcg() function they can be added to a bytearray variable and returned at the end of the function. For example:

print("The formula is: X(k+1) = a * Xk + c mod m")
seed_num = 9999  # int(input("Enter seed number: "))
multiplier = 14  # int(input("Enter the multiplier(a): "))
increment = 12  # int(input("Enter the increment(c): "))
modulus = 128  # int(input("Enter the modulus (m): "))
unit = 4  # int(input("How many random numbers would you like to generate?\nInput: "))


def lcg():
    result = bytearray()
    num_base = seed_num
    for i in range(unit, 0, -1):
        rd = (multiplier * num_base + increment) % modulus
        print(rd)
        num_base = rd
        result.append(rd)
    return result


lcg_result = lcg()
print(f"raw bytearray: {lcg_result}")
print(f"As list: {list(lcg_result)}")
print(f"As hex value: {lcg_result.hex()}")

Which gave the following output:

The formula is: X(k+1) = a * Xk + c mod m
94
48
44
116
raw bytearray: bytearray(b'^0,t')
As list: [94, 48, 44, 116]
As hex value: 5e302c74
Related