如何对浮点数执行按位运算

float a = 1.4123; a = a & (1 << 3);

float a = 1.4123; a = (int)a & (1 << 3);

float a = 1.4123; a = (void*)a & (1 << 3);

float f = 5; unsigned char *c = reinterpret_cast<unsigned char *>(&f); // inspect memory from c[0] to c[sizeof f - 1]

union fp_bit_twiddler { float f; int i; } q; qf = a; qi &= (1 << 3); a = qf;

float a = 1.4123; unsigned int* inta = reinterpret_cast<unsigned int*>(&a); *inta = *inta & (1 << 3);

#include <iostream> using namespace std; int main() { float x, td = 2.0; int ti = *(int*) &td; cout << "Cast int: " << ti << endl; ti = ti>>4; x = *(float*) &ti; cout << "Recast float: " << x << endl; return 0; }

@mobrule：

#include <stdint.h> ... union fp_bit_twiddler { float f; uint32_t u; } q; /* mutatis mutandis ... */

// Simple object wrapper for float type as templates want classes. class Float { float m_f; public: Float( const float & f ) : m_f( f ) { } operator float() const { return m_f; } }; float operator>>( const Float & left, int right ) { float temp = left; for( right; right > 0; --right ) { temp /= 2.0f; } return temp; } float operator<<( const Float & left, int right ) { float temp = left; for( right; right > 0; --right ) { temp *= 2.0f; } return temp; } int main( int argc, char ** argv ) { int a1 = 40 >> 2; int a2 = 40 << 2; int a3 = 13 >> 2; int a4 = 256 >> 2; int a5 = 255 >> 2; float f1 = Float( 40.0f ) >> 2; float f2 = Float( 40.0f ) << 2; float f3 = Float( 13.0f ) >> 2; float f4 = Float( 256.0f ) >> 2; float f5 = Float( 255.0f ) >> 2; }

float a = 1.4123; int *b = (int *)&a; *b = *b & (1 << 3); // a is now the IEEE floating-point value caused by the manipulation of *b // equals 1.121039e-44 (tested on my system)

FWIW，在浮点运算上有一个真实的用例（我刚刚碰到它） – 为仅支持GLSL的老版本的GPU编写的着色器（1.2及更早版本不支持按位运算符） ，如果浮点数转换为整数，那么精度会有所下降。

float A = 0.625; //value to check; ie, 160/256 float mask = 0.25; //bit to check; ie, 1/4 bool result = (mod(A, 2.0 * mask) >= mask); //non-zero if bit 0.25 is on in A

float mod(float num, float den) { return num - den * floor(num / den); }