c/c++语言开发共享IEEE 754到C语言的十进制

我正在寻找将浮点数转换为C中的十进制表示的最佳方法。我将尝试给出一个示例:用户在IEEE754(1 1111111 10101 …)中引入一个数字,程序必须返回十进制表示(例如25.6)
我尝试过使用掩码和按位操作,但我没有任何逻辑结果。

    我相信以下是执行您描述的操作:

    我使用int作为中间表示,因为它与float(在我的机器上)具有相同的位数,并且允许从二进制字符串轻松转换。

     #include  union { int i; float f; } myunion; int binstr2int(char *s) { int rc; for (rc = 0; '' != *s; s++) { if ('1' == *s) { rc = (rc * 2) + 1; } else if ('0' == *s) { rc *= 2; } } return rc; } int main(void) { // the input binary string (4 bytes) char * input = "11000000110110011001100110011010"; float *output; // convert to int, sizeof(int) == sizeof(float) == 4 int converted = binstr2int(input); // strat 1: point memory of float at the int output = (float*)&converted; // cast to suppress warning printf("%fn", *output); // -6.8 // strat 2: use a union to share memory myunion.i = converted; printf("%fn", myunion.f); // -6.8 return 0; } 

    正如@DanielKamilKozar指出的那样,该int的正确类型是uint32_t 。 但是,这需要包括

      以上就是c/c++开发分享IEEE 754到C语言的十进制相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/523292.html

      (0)
      上一篇 2020年12月11日
      下一篇 2020年12月11日

      精彩推荐