【问题标题】:Arduino convert float to hex IEEE754 Single precision 32-bitArduino 将浮点数转换为十六进制 IEEE754 单精度 32 位
【发布时间】:2020-11-12 21:49:51
【问题描述】:

我想在Arduino的以下站点中将浮点值转换为IEEE754单精度32位十六进制值。 https://www.binaryconvert.com/result_float.html?decimal=051046049048

float f = 3.10;
byte hex[4] = {0};

byte FloatToHex(float f){
   .......
}

如何创建这样的函数? 格式不一样也没关系。

【问题讨论】:

    标签: arduino 32-bit ieee-754 single-precision


    【解决方案1】:

    f 已经以二进制形式存储。 reinterpret_cast 通常是代码异味问题,但它的有效用途是查看变量的字节表示。

    
    void FloatToHex(float f, byte* hex){
      byte* f_byte = reinterpret_cast<byte*>(&f);
      memcpy(hex, f_byte, 4);
    }
    
    void setup() {
      float f = 3.10;
      byte hex[4] = {0};
    
      FloatToHex(f, hex);
      //... do stuff with hex now...
    }
    
    void loop() {
      
    }
    

    【讨论】:

    • 效果很好!太感谢了。 //:D_b 但是,对于使用此代码的人有一个警告。可能存在 hex[4] 数组中的数据反转的情况。 (不是大端)这样的话,你可以在循环中倒序保存和使用数据。
    • 在此警告 - 大端或小端不是随机的,无论您构建的架构(处理器)都将记录其字节序。如果您遇到这种情况并且不知道您的系统是大端还是小端,请在文档中查找!
    猜你喜欢
    • 2011-03-05
    • 2014-02-07
    • 2014-03-01
    • 2011-09-18
    • 2012-08-22
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多