問題描述
Arduino 將浮點數轉換為十六進制 IEEE754 單精度 32 位 (Arduino convert float to hex IEEE754 Single precision 32‑bit)
我想在Arduino的以下站點中將浮點值轉換為IEEE754單精度32位十六進制值。https://www.binaryconvert.com/result_float.html?decimal=051046049048
float f = 3.10;
byte hex[4] = {0};
byte FloatToHex(float f){
.......
}
如何創建這樣的函數?格式不一樣也沒關係。
參考解法
方法 1:
f
is already stored in binary. reinterpret_cast
is generally a code smell issue, but its valid use is to view the byte representation of variables.
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() {
}
(by WooJae You、JohnFilleau)