以浮点或双精度形式获取字节值。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了以浮点或双精度形式获取字节值。相关的知识,希望对你有一定的参考价值。

This routine can be used to copy the byte values of a float or double. The "isBigEndian" variable needs to be determined (most PCs are little-endian, whereas most embedded microprocessors are big-endian). Instead of using unsigned chars, it can be useful to do a "typedef unsigned char UINT8" and simply use UINT8 as the variable type.
  1. float aFloat = anotherFloat; // Could be a double instead
  2. unsigned char bytes[sizeof(float)];
  3. unsigned char *byte = (unsigned char *) &aFloat;
  4.  
  5. if(isBigEndian)
  6. {
  7. for (i=0; i<sizeof(float); i++)
  8. {
  9. bytes[i] = *byte;
  10. byte++;
  11. }
  12. }
  13. else
  14. {
  15. for (i=sizeof(float)-1; i>=0; i--)
  16. {
  17. bytes[i] = *byte;
  18. byte++;
  19. }
  20. }

以上是关于以浮点或双精度形式获取字节值。的主要内容,如果未能解决你的问题,请参考以下文章

float的取值范围怎么计算

float和double有啥区别?

可以将浮点(或双精度)设置为 NaN 吗?

从二进制形式转换浮点 NaN 值,反之亦然导致不匹配

在python中 float是啥意思?

C语言中float是啥意思