以下は、共用体と整数ビットフィールドを使用した型パニング浮動小数点値の例です。
#include <iostream>
union floatPun {
struct {
unsigned int mantissa : 23;
unsigned int exponent : 8;
unsigned int sign : 1;
};
float value;
};
union doublePun {
struct {
unsigned long long mantissa : 52;
unsigned long long exponent : 11;
unsigned long long sign : 1;
};
float value;
};
template <typename PunT>
static int compare_mantissas(const PunT& a, const PunT& b) {
return int(a.mantissa > b.mantissa) - (b.mantissa > a.mantissa);
}
int main() {
floatPun fa = {0}, fb = {0};
// make NaNs
fa.exponent = fb.exponent = 0xff;
fa.mantissa = 1;
fb.mantissa = 2;
std::cout << "fa: " << fa.value << " fb: " << fb.value << "\n";
// compare mantissas
static const char* const cmp_labels[] = {"less than", "equal to", "greater than"};
std::cout << "mantissa of fa is "
<< cmp_labels[1 + compare_mantissas(fa, fb)]
<< " mantissa of fb\n";
// change fa to +infinity
fa.mantissa = 0;
std::cout << "changed fa's mantissa to zero: " << fa.value << "\n";
}