如何将 Float 小数部分的前 32 位转换为 Word32?

发布于 2024-11-06 09:14:19 字数 735 浏览 5 评论 0原文

说我有一个漂浮物。我想要这个 Float 的小数部分的前 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] ?

Say I have a Float. I want the first 32 bits of the fractional part of this Float? Specifically, I am looking at getting this part of the sha256 pseudo-code working (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

I naively tried doing floor (((sqrt 2) - 1) * 2^32), and then converting the returned integer to a Word32. This does not at all appear to be the right answer. I figured that by multipling by 2^32 power, I was effectively left shifting it 32 places (after the floor). Obviously, not the case. Anyway, long and the short of it is, how do I generate h[0..7] ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

橘虞初梦 2024-11-13 09:14:19

获取 h[0..7] 的最佳方法是从维基百科页面复制十六进制常量。这样您就知道您将拥有正确的。

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

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

The best way to get h[0..7] is to copy the hex constants from the Wikipedia page. That way you know you will have the correct ones.

But if you really want to compute them:

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] ]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文