카테고리 없음2015. 3. 10. 01:16

csapp2e를 보다가 작성해서 테스트 해 본 코드.

math.h에 NAN은0x7fc00000 로 정의되어 있다. 그러나 이 floating point 밸류를 NAN과 비교해 판별하면 무조건 다르게 나온다는 점. NaN을 판별하려면 isnan() 함수를 사용하거나, exponent bits를 봐야 할 듯.




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//
//  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");
 
}



Posted by 쿨한넘