How do I use bitwise operators on a “double” on C++?

后端 未结 6 1526
遇见更好的自我
遇见更好的自我 2020-12-17 22:16

I was asked to get the internal binary representation of different types in C. My program currently works fine with \'int\' but I would like to use it with \"double\" and \"

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-17 23:18

    Other solution is to get a pointer to the floating point variable and cast it to a pointer to integer type of the same size, and then get value of the integer this pointer points to. Now you have an integer variable with same binary representation as the floating point one and you can use your bitwise operator.

    string findBin(float f) {
        string binary;
        for(long i = 4096 ; i >= 1; i/=2) {
            long x = * ( long * ) &y;
            if((x & i) != 0) binary += "1";
            else binary += "0";
        }
        return binary;
    }
    

    But remember: you have to cast to a type with same size. Otherwise unpredictable things may happen (like buffer overflow, access violation etc.).

提交回复
热议问题