开发者

What are the first 32 bits of the fractional part of this float?

I am looking at the following SHA256 pseudocode on wikipedia.

Specifically, I am looking at the following section.

//Initialize variables
//(first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):
h0 := 0x6a09e667

I am trying to figure out how h0 was generated. I know from the comment that this should be the fractional part of the square root of 2. I believe I can get the fractional part of the square root of 2 by typing the following. All the following code is from the python repl.

>>> math.modf(math.sqrt(2))[0]
0.41421356237309515

At the top of the file it states that the declaration of all constants are Big Endian. I know that my environment is Small Endian because I type.

>>> import sys
>>> sys.byteorder
'little'

So, according to my manual manipulation of the hex value in h0, the Little Endian representation should be 0x67e6096a.

>>> int(0x67e6096a)
1743128938

And I am stuck. I have tried various manipulations, but non of them end up开发者_运维问答 with this result. I do not know how to get the first 32 bits of the fractional part of a floating point number. I know that somehow my 0.41421356237309515 (float) result can be transformed into 1743128938 (int), but I really have no idea how. What are the steps necessary to get the first 32 bits of the fractional part of a floating point number? Python answers only please.

Thank you.


  1. Use your calculator on Windows to calculate sqrt(2) (1.4142135623730950488016887242097)
  2. Take the decimal part (0.4142135623730950488016887242097)
  3. Multiply by 2^32 (1779033703.9520993849027770600526)
  4. Express the whole part in hex (6A09E667)

Voila. (Apologies to OP for not doing a Python answer but I hope the method is clear.)


Endianness does not matter for hexadecimal constants; each digit is a nibble, with the least significant nibble last. It does matter if you deal with differing size pointers. If you do need to use byte orders, the struct module can help. Anyhow, you've retrieved the fractional part just fine; converting it to hex is easily done by simply multiplying and truncating, so we get an integer:

>>> hex(int(math.modf(math.sqrt(2))[0]*(1<<32)))
'0x6a09e667'


Python can display the exact IEEE 754 floating point data as a hexadecimal value. It includes the implied leading 1, the mantissa in hex and the exponent value:

>>> math.sqrt(2).hex()
'0x1.6a09e667f3bcdp+0'

Slice as needed, for example:

>>> '0x'+math.sqrt(2).hex().split('.')[1][:8]
'0x6a09e667'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜