はじめに
センサーやデバイスと UART などで通信をしていると、浮動小数点数を IEEE754 でやり取りしたいことが多いので、そのための備忘メモです。
Python の場合
Python の場合、struct モジュールの pack
/ unpack
を使います。
ビッグエンディアンでバイト列に変換する場合以下のようになります。
>>> import struct
>>> value = 128.54
>>> buff = struct.pack('>f', value)
>>> print(buff.hex())
43008a3d
https://gregstoll.dyndns.org/~gregstoll/floattohex/ で、 0x43008a3d
がいくつかを確認します。
128.54
であることが確認できました。
戻すときは、同様に unpack
を使います。
>>> import struct
>>> buff = bytes([0x43, 0x00, 0x8a, 0x3d])
>>> value = struct.unpack('>f', buff)[0]
>>> print(value)
128.5399932861328
JavaScript の場合
JavaScript の場合、 ArrrayBuffer
を使用します。
const os = require('os');
const data = Buffer.from([0x43, 0x00, 0x8a, 0x3d]);
const buffer = new ArrayBuffer(4);
const f32 = new Float32Array(buffer);
const ui8 = new Uint8Array(buffer);
if (os.endianness() === 'LE') {
ui8[0] = data[3];
ui8[1] = data[2];
ui8[2] = data[1];
ui8[3] = data[0];
} else {
ui8[0] = data[0];
ui8[1] = data[1];
ui8[2] = data[2];
ui8[3] = data[3];
}
console.log(f32[0]);