double to hex string & hex string to double

后端 未结 9 1379
南方客
南方客 2021-01-02 20:51

What I\'m trying to do is to convert a double to hex string and then back to double.

The following code does conversion double-to-hex string.

char *          


        
9条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-02 21:24

    You want to use a union and avoid this bad habit:

    char *d2c;

    d2c = (char *) &a;

    For just printing its not bad, its when you try to modify d2c and then use a is when you get into trouble. (same is true for any two variables or pointers (or arrays) sharing the same (theoretical) memory.

    union
    {
        double f;
        unsigned long ul;
    } myun;
    
    myun.f = a;
    printf("0x%lX",myun.ul);
    
    to go the other way (scanf is also a very dangerous function that should be avoided).
    
    myun.ul=strtoul(string,NULL,16);
    a=myun.f;
    

提交回复
热议问题