UNPKG

729 BJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3
4/**
5 * @name u8aToFloat
6 * @description Converts a Uint8Array value into the float (either 32 or 64-bit)
7 * representation.
8 */
9export function u8aToFloat(value, {
10 bitLength = 32,
11 isLe = true
12} = {}) {
13 if (bitLength !== 32 && bitLength !== 64) {
14 throw new Error('Invalid bitLength provided, expected 32 or 64');
15 } else if (value.length < bitLength / 8) {
16 throw new Error(`Invalid input buffer provided, expected at least ${bitLength / 8} bytes, found ${value.length}`);
17 }
18
19 const dv = new DataView(value.buffer, value.byteOffset);
20 return bitLength === 32 ? dv.getFloat32(0, isLe) : dv.getFloat64(0, isLe);
21}
\No newline at end of file