csapp2e를 보다가 작성해서 테스트 해 본 코드.
math.h에 NAN은0x7fc00000 로 정의되어 있다. 그러나 이 floating point 밸류를 NAN과 비교해 판별하면 무조건 다르게 나온다는 점. NaN을 판별하려면 isnan() 함수를 사용하거나, exponent bits를 봐야 할 듯.
// // main.c // floatingpoint_bits // // Created by Seong-Su Kim on 2015. 3. 9.. // Copyright (c) 2015년 Seong-Su Kim. All rights reserved. // #include <stdio.h> #include <math.h> void printfpValue(float fvalue); void printbitsValue(unsigned bits); void isNaN(unsigned bits); int main(void) { unsigned long count; unsigned long start, end; printf("\n# predefined values\n\n"); printfpValue(NAN); printfpValue(INFINITY); if (NAN == NAN) printf("NAN == NAN!\n"); // will be never executed printf("\n\n# user bits to floating point value\n\n"); printbitsValue(0xff800000); isNaN(0xff800000); printbitsValue(0x7f800001); isNaN(0x7f800001); printbitsValue(0x7fc00000); isNaN(0x7fc00000); printbitsValue(0xff800001); isNaN(0xff800001); printf("enter start value : "); scanf("%lx", &start); printf("start value = %#lx\n", start); printf("enter end value : "); scanf("%lx", &end); printf("end value = %#lx\n", start); for (count = start; count <= end; count++) printbitsValue((unsigned)count); return 0; } void printfpValue(float fvalue) { unsigned *bp; bp = (unsigned *)(&fvalue); printf("%0#10x = %12e\n", *bp, fvalue); } void printbitsValue(unsigned bits) { float *fp; fp = (float *)(&bits); printf("%0#10x = %12e\n", bits, *fp); } void isNaN(unsigned bits) { float *fp; fp = (float *)(&bits); if (*fp == NAN) printf("%e == NAN,\t", *fp); else printf("%e != NAN,\t", *fp); if (isnan(*fp)) printf("isnan() says it is NaN.\n\n"); else printf("isnan() says it is not NaN.\n\n"); }