How to see a numeric representation in binary floating point format

For example, I have a number 0.1:

double n = 0.1;

It is presented in the IEEE-754 large endian as:

0 01111111011 1001100110011001100110011001100110011001100110011010

How can I output 0.1to this binary format?

+4
source share
2 answers

To convert double to binary, you need to call Double.doubleToLongBits(x)and Long.toBinaryString(x).

So you can try String binary = Long.toBinaryString( Double.doubleToLongBits(0.1) );

To get the full 64-bit representation, you would need to add up to the 0th number.

Edit

Since you asked for the C version, I will try to add one (although I am not a C expert, so I could skip something like the std lib functions):

#include <stdio.h>
#include <stdint.h>

union binary {
    double d;
    uint64_t l;
} binary;

int main() {
    union binary b;
    b.d = 0.1; //set the value as double

    uint64_t bin = b.l; //read the value as 64-bit unsigned integer

    char c[65];
    c[64] = '\0'; //string terminator
    //iterate from 63 to 0
    for( int i = sizeof(uint64_t) * 8 - 1; i >= 0; i--) {
        if( bin & 1 ) {
            c[i]='1';
        } else {
            c[i]='0';
        }

        bin >>= 1; //right-shift by 1, i.e. 0010 -> 0001 etc.
    }                                                                                                                                             
    printf("%s\n",c);

    return 0;
}

union, double 64- (aka long long). , , , , , 1.

, : double dbl = 0.1; uint64_t bin = *((uint64_t*)(&dbl)); ( , -, , ).

: , (.. ), .

+1

Float Float.floatToIntBits

final int intBits = Float.floatToIntBits(4.1f);
final String binary = Integer.toBinaryString(intBits);
System.out.println(binary);

fusses ...

https://www.h-schmidt.net/FloatConverter/IEEE754.html

+5

Source: https://habr.com/ru/post/1656776/


All Articles