生成数字并放入字节数组



这个想法是使用线性同余生成器生成非加密数字。它有一个内部状态,由最初设置为x0=seed的数字xi组成。我需要从这个生成器中取出给定长度的输出字节。

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()  

我需要从使用这个LCG代码生成的内容中获得一个字节数组。我需要输出字节,从第一次迭代中生成的字节开始,到最后一次迭代中产生的字节结束。

我想您正在寻找bytearray()函数。

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'x10x19%5x01x05/0x1f-x1bx03x1ax14x0c&$x0f*x17x10x19%5x01x05/0x1f-x1bx03x1ax14x0c&$x0f*x17x10x19%5x01x05/0x1f-x1bx03x1ax14x0c&$x0f')

如果你只想把数字转换成字节,你也可以这样做:

bytes([x])

其中x是从0到255的整数。

如果这不是你想要的,请添加一个你想做什么的例子。

当字节在lcg()函数中创建时,它们可以添加到字节数组变量中,并在函数末尾返回。例如:

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()}")

它给出了以下输出:

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

最新更新