我无法理解python中的from_bytes()
方法对于以下代码实例的确切作用。特别是如何创建以255开头并以25个零开头的字节数组会产生整数值。
我对了解以下行的内部运作特别感兴趣int.from_bytes(byte_seed, byteorder="big", signed=False)
在代码中:
def test_base_hash_from_wisconsin(self):
q: int = pow(2, 256) - 189
q_static = 115792089237316195423570985008687907853269984665640564039457584007913129639747
# Verify the correct value for q is used
self.assertEqual(q, q_static)
# Create a byte array with 0xff & 25 zeroes
byte_seed = bytes([
255,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0,
])
# convert the byte array to an integer deterministically
as_int = int.from_bytes(byte_seed, byteorder="big", signed=False)
print(as_int)
# take the integer mod q
base_hash = as_int % q
print(base_hash)
self.assertEqual(base_hash, as_int)
self.assertEqual(
base_hash, 409769201286042520263200333546996463643161763414612173001850880
)
这是做相同事情的原始C代码:
void Crypto_hash_reduce(struct hash *out, raw_hash bytes)
{
mpz_import(out->digest, HASH_DIGEST_SIZE_BYTES / 8, 1, 8, 0, 0, bytes);
mod_q(out->digest, out->digest);
}
整数在存储器中被保存为一系列0和1,例如:
Unsigned int
0 -> 00000000 00000000
1 -> 00000000 00000001
2 -> 00000000 00000010
3 -> 00000000 00000011
...
65536 -> 11111111 11111111
Signed int
-32768 -> 10000000 00000000
...
-2 -> 11111111 11111110
-1 -> 11111111 11111111
0 -> 00000000 00000000
1 -> 00000000 00000001
2 -> 00000000 00000010
3 -> 00000000 00000011
...
32767 -> 01111111 11111111
现在,我使用了“大端优先”类型的解码,其中最高有效字节在前。
还有“小尾数”:
无符号整数(小尾数)
0 -> 00000000 00000000 1 -> 00000001 00000000 2 -> 00000010 00000000 3 -> 00000011 00000000 ... 65536 -> 11111111 11111111
注意字节是如何交换的,但是字节内部的位顺序是相同的。
int.from_bytes
所做的只是使用此精确协议将一系列0和1转换为整数
如果您想进一步了解该主题,请搜索诸如binary number
,endianness
之类的关键字,或查阅诸如此类的链接