How to convert the first 32 bits of the Float fraction to Word32?

Say I have a float. I want the first 32 bits of the fractional part of this float? In particular, I am considering getting this part of the sha256 pseudocode ( from 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 to do the gender ((((sqrt 2) - 1) * 2 ^ 32), and then converted the returned integer to Word32. This, apparently, is not the correct answer. I thought that by multiplying the force by 2 ^ 32, I actually left it 32 places (after the floor). Obviously, this is not the case. Anyway, long and short, how do I generate h [0..7]?

+4
source share
1 answer

The best way to get h [0..7] is to copy the hexadecimal constants from the Wikipedia page. So you know that you will have the right ones.

But if you really want to calculate 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] ] 
+5
source

All Articles