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

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

    Do a bit-wise cast of a pointer to the double to long long * and dereference. Example:

    inline double bit_and_d(double* d, long long mask) {
      long long t = (*(long long*)d) & mask;
      return *(double*)&t;
    }
    

    Edit: This is almost certainly going to run afoul of gcc's enforcement of strict aliasing. Use one of the various workarounds for that. (memcpy, unions, __attribute__((__may_alias__)), etc)

提交回复
热议问题