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

后端 未结 3 1265
遇见更好的自我
遇见更好的自我 2021-02-05 21:20

I am looking at the following SHA256 pseudocode on wikipedia.

Specifically, I am looking at the following section.

//Initialize variables
//(first 32 bits          


        
相关标签:
3条回答
  • 2021-02-05 22:18

    Python can 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 讨论(0)
  • 2021-02-05 22:24
    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.)

    0 讨论(0)
  • 2021-02-05 22:25

    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'
    
    0 讨论(0)
提交回复
热议问题