0

I am receiving a Buffer 40 48 f5 c3 3f b4 7a e1 3f 35 c2 8f with the following values, the values are coded as Float32 :

3.14: 0x4048f5c3
1.41: 0x3fb47ae1
0.71: 0x3f35c28f

Can I map the buffer into a json as a row of numbers:

{
  value1: 3.14,
  value2: 1.41,
  value3: 0.71,
}

or into a Array as numbers [3.14, 1.41, 0.71]

MeerArtefakt
  • 386
  • 2
  • 6
  • 26
  • 1
    Does this answer your question? [JavaScript convert Array of 4 bytes into a float value from modbusTCP read](https://stackoverflow.com/questions/42699162/javascript-convert-array-of-4-bytes-into-a-float-value-from-modbustcp-read) – collapsar Jun 27 '22 at 09:36
  • 1
    I used the method in the other question, and got `3.140000104904175`, `1.409999966621399` and `0.7099999785423279` respectively. Those are the same as `Math.fround(3.14)`, `Math.fround(1.41)` and `Math.fround(0.71)`, respectively. I am wondering if there is a reliable way to convert them to (js numbers) `3.14`, `1.41` and `0.71`. – qrsngky Jun 28 '22 at 09:36
  • 1
    I can use something like `+Math.fround(0.71).toPrecision(7)` but I'm not sure if it will work in all cases. – qrsngky Jun 28 '22 at 10:30
  • 1
    `Math.fround(0.10000001)` and `Math.fround(0.10000002)` are different but setting precision to 7 simply gives `'0.1000000'` – qrsngky Jun 28 '22 at 10:37

1 Answers1

0

My solution from an existing answer from another question:

For decoding a float coded in Big Endian (ABCD) with Node.js:

const buffer = [
  0x40, 0x48, 0xf5, 0xc3,
  0x3f, 0xb4, 0x7a, 0xe1,
  0x3f, 0x35, 0xc2, 0x8f];

const firstValue = Buffer.from(buffer).readFloatBE(0); // 3.14
const secondValue = Buffer.from(buffer).readFloatBE(4) // 1.41
const thirdValue = Buffer.from(buffer).readFloatBE(8) // 0.71
MeerArtefakt
  • 386
  • 2
  • 6
  • 26
  • edit: I just used `someValue.toFixed(2)` for getting 3.14 / 1.41. / 0.71 – MeerArtefakt Feb 22 '23 at 14:07
  • 1
    It's useful if you know that each number has at most 2 decimal places. However, I wonder if there is a reliable way to produce a float32 representation like other languages. When I tried `.toPrecision(7)`, I found that it's not completely reliable as `0.10000001` and `0.10000002` have different results for fround, but became the same after using toPrecision. However, when attempting to be more precise, when I tried `.toPrecision(8)`, the result from processing `3.14` is `3.1400001` (they are the same when `fround`-ed, though). – qrsngky Feb 23 '23 at 02:11