How to convert float number to Binary?

前端 未结 6 808
不思量自难忘°
不思量自难忘° 2020-12-07 16:53

Can anyone please tell me how can I convert this float number: 12.25 to binary? I know how to convert the \"12\" but not the 0.25

Any help is much appreciated. Thank

相关标签:
6条回答
  • 2020-12-07 17:12
    void transfer(double x) {
    unsigned long long* p = (unsigned long long*)&x;
    for (int i = sizeof(unsigned long long) * 8 - 1; i >= 0; i--) {cout<< ((*p) >>i & 1);}}
    
    0 讨论(0)
  • 2020-12-07 17:13

    (d means decimal, b means binary)

    1. 12.25d is your float.
    2. You write 12d in binary and remove it from your float. Only the remainder (.25d) will be left.
    3. You write the dot.
    4. While the remainder (0.25d) is not zero (and/or you want more digits), multiply it with 2 (-> 0.50d), remove and write the digit left of the dot (0), and continue with the new remainder (.50d).
    0 讨论(0)
  • 2020-12-07 17:14
    x = float(raw_input("enter number between 0 and 1: "))
    
    p = 0
    while ((2**p)*x) %1 != 0:
        p += 1
        # print p
    
        num = int (x * (2 ** p))
        # print num
    
        result = ''
        if num == 0:
            result = '0'
        while num > 0:
            result = str(num%2) + result
            num = num / 2
    
        for i in range (p - len(result)):
            result = '0' + result
        result = result[0:-p] + '.' + result[-p:]
    
    print result #this will print result for the decimal portion
    
    0 讨论(0)
  • Consider below example

    Convert 2.625 to binary.

    We will consider the integer and fractional part separately.

    The integral part is easy, 2 = 10. 
    

    For the fractional part:

    0.625   × 2 =   1.25    1   Generate 1 and continue with the rest.
    0.25    × 2 =   0.5     0   Generate 0 and continue.
    0.5     × 2 =   1.0     1   Generate 1 and nothing remains.
    

    So 0.625 = 0.101, and 2.625 = 10.101.

    See this link for more information.

    0 讨论(0)
  • 2020-12-07 17:31

    The float value is stored in IEEE 754 format so we can't convert it directly like integer, char to binary.

    But we can convert float to binary through a pointer.

    #include <stdio.h>
    
    int main()
    {
        float a = 7.5;
        int i;
        int * p;
    
        p = &a;
        for (i = sizeof(int) * 8 - 1; i >= 0; i--)
        {   
            printf("%d", (*p) >> i & 1); 
        }   
    
        return 0;
    }
    

    Output

    0 10000001 11100000000000000000000
    

    Spaces added for clarification, they are not included as part of the program.

    0 讨论(0)
  • 2020-12-07 17:34

    Keep multiplying the number after decimal by 2 till it becomes 1.0:

    0.25*2 = 0.50
    0.50*2 = 1.00
    

    and the result is in reverse order being .01

    0 讨论(0)
提交回复
热议问题