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

后端 未结 6 1564
遇见更好的自我
遇见更好的自我 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 22:58

    As others have said, you can use a bitwise operator on a double by casting double* to long long* (or sometimes just long*).

    int main(){
        double * x = (double*)malloc(sizeof(double));
        *x = -5.12345;
        printf("%f\n", *x);
        *((long*)x) &= 0x7FFFFFFFFFFFFFFF;
        printf("%f\n", *x);
        return 0;
    }
    

    On my computer, this code prints:

    -5.123450
    5.123450
    

提交回复
热议问题