I'm toying with implementing NaN tagging in a little language implementation I'm writing in C. To do this, I need to take a double and poke directly at its bits.
I have it working now using union casting:
typedef union
{
double num;
unsigned long bits;
} Value;
/* A mask that selects the sign bit. */
#define SIGN_BIT (1UL << 63)
/* The bits that must be set to indicate a quiet NaN. */
#define QNAN (0x7ff8000000000000L)
/* If the NaN bits are set, it's not a number. */
#define IS_NUM(value) (((value).bits & QNAN) != QNAN)
/* Convert a raw number to a Value. */
#define NUM_VAL(n) ((Value)(double)(n))
/* Convert a Value representing a number to a raw double. */
#define AS_NUM(value) (value.num)
/* Converts a pointer to an Obj to a Value. */
#define OBJ_VAL(obj) ((Value)(SIGN_BIT | QNAN | (unsigned long)(obj)))
/* Converts a Value representing an Obj pointer to a raw Obj*. */
#define AS_OBJ(value) ((Obj*)((value).bits & ~(SIGN_BIT | QNAN)))
But casting to a union type isn't standard ANSI C89. Is there a reliable way to do this that:
- Is
-std=c89 -pedantic
clean? - Doesn't run afoul of strict aliasing rules?
Can be used in an expression context like this:
Value value = ... printf("The number value is %f\n", AS_NUM(value));