我正在尝试用我用 C 编写的一种小语言实现来实现NaN 标记。为此,我需要取一个 double 并直接戳它的位。
我现在使用联合铸造让它工作:
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)))
但是转换为联合类型不是标准的 ANSI C89。有没有可靠的方法来做到这一点:
-std=c89 -pedantic
干净吗?- 不违反严格的别名规则吗?
可以在这样的表达式上下文中使用:
Value value = ... printf("The number value is %f\n", AS_NUM(value));