4

说我有一个浮动。我想要这个浮点数小数部分的前 32 位?具体来说,我正在考虑让这部分 sha256 伪代码工作(来自维基百科

# Note 1: All variables are unsigned 32 bits and wrap modulo 232 when calculating
# Note 2: All constants in this pseudo code are in big endian

# Initialize variables
# (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
h[0..7] := 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19

我天真地尝试做 floor (((sqrt 2) - 1) * 2^32),然后将返回的整数转换为 Word32。这似乎根本不是正确的答案。我想通过乘以 2^32 次幂,我实际上是左移了 32 个位置(在地板之后)。显然,情况并非如此。无论如何,总而言之,我如何生成 h[0..7] ?

4

1 回答 1

5

获得 h[0..7] 的最佳方法是从 Wikipedia 页面复制十六进制常量。这样你就知道你会得到正确的。

但如果你真的想计算它们:

scaledFrac :: Integer -> Integer
scaledFrac x =
    let s = sqrt (fromIntegral x) :: Double
    in  floor ((s - fromInteger (floor s)) * 2^32)

[ printf "%x" (scaledFrac i) | i <- [2,3,5,7,11,13,17,19] ]
于 2011-05-08T07:37:23.443 回答