0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

浮動小数点数をバイト列で交換する

Posted at

はじめに

センサーやデバイスと 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 がいくつかを確認します。

image.png

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]);
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?