Pergunta

Estou brincando com a implementação Marcação NaN em uma pequena implementação de linguagem estou escrevendo em C.Para fazer isso, preciso pegar um duplo e cutucar diretamente seus pedaços.

Eu tenho isso funcionando agora usando conversão de união:

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)))

Mas a conversão para um tipo de união não é o padrão ANSI C89.Existe uma maneira confiável de fazer isso:

  1. É -std=c89 -pedantic limpar?
  2. Não entra em conflito com regras rígidas de alias?
  3. Pode ser usado em um contexto de expressão como este:

    Value value = ...
    printf("The number value is %f\n", AS_NUM(value));
    
Foi útil?

Solução

Aqui está uma rápida prova de conceito que compila de forma limpa e parece funcionar corretamente para mim.eu uso memcpy para refinar a questão do trocadilho.É claro que isso pode ser inaceitável em um sistema real, mas é pelo menos portátil.Da mesma forma, não sei se você pretende exigir isso AS_NUM ser implementado como uma macro.

#include <stdio.h>
#include <string.h>

typedef struct {
    char raw[sizeof(double)];
} Value;

static Value valueFromDouble(double d) {
    Value result;
    memcpy(result.raw, &d, sizeof(result));
    return result;
}

static double AS_NUM(Value value) {
    double result;
    memcpy(&result, value.raw, sizeof(result));
    return result;
}

int main(int argc, char **argv) {
    Value value = valueFromDouble(1.0);
    printf("The number value is %f\n", AS_NUM(value));
}

Aqui está uma transcrição da compilação (com Clang no OS X) e execução:

$ cc -std=c89 -pedantic blort.c
$ ./a.out
The number value is 1.000000
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top