【问题标题】:How do I convert the first 32 bits of the fractional part of a Float into a Word32?如何将浮点数小数部分的前 32 位转换为 Word32?
【发布时间】:2012-05-17 03:21:16
【问题描述】:

假设我有一个浮动。我想要这个浮点数小数部分的前 32 位?具体来说,我正在考虑让这部分 sha256 伪代码工作 (from the wikipedia)

# 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] ?

【问题讨论】:

  • 请注意,浮点数中的任何内容都没有 32 位精度。

标签: haskell floating-point sha256 sha


【解决方案1】:

获得 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] ]

【讨论】:

  • 我认为他想获得表示的第一部分。
  • 他想要我的代码给他的位。我检查了维基百科条目。
  • 哈哈,是的,我不敢相信我没有想到自己只是复制和粘贴常量。我想我现在有两种生成 h[0..7] 的方法。谢谢
  • 我试图理解计算,但我似乎无法理解为什么小数部分乘以 2^32。你能解释一下吗?
  • @STT Computing s - fromInteger (floor s) 在区间 (0,1() 中给出一个数字。要获得 32 位整数,我们乘以 2^32。
猜你喜欢
  • 2011-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多