• Node.js Video Tutorials

Node.js - Buffer.writeFloatLE() 方法



Node.JS Buffer.writeFloatLE() 方法用於將一個小端序的 32 位浮點數寫入當前緩衝區物件的指定偏移量處。

32 位浮點數也稱為 FP32 或 float32。使用時,它在計算機中佔用 32 位記憶體。

32 位浮點數被劃分為符號位、指數位和尾數位。符號位佔用 1 位,指數位佔用 8 位,其餘 24 位(其中 23 位用於顯式儲存)由尾數位佔用。

  • 符號位表示數字的正負號。

  • 指數位是一個 8 位無符號整數,最小值為 0,最大值為 255。

  • 尾數位是 24 位。例如,一個數字是 125.3。因此,這裡的整數 1253 是尾數,$10^{-1}$ 是冪項,-1 是指數。

語法

以下是 Node.JS Buffer.writeFloatLE() 方法 的語法:

buf.writeFloatLE(value[, offset])

引數

此方法接受兩個引數。下面解釋了這兩個引數。

  • value − (必填)要寫入緩衝區的值。

  • offset − (可選)此處的偏移量指示開始寫入的位置。偏移量大於或等於 0,並且小於或等於 buffer.length-4。預設值為 0。

返回值

Buffer.writeFloatLE() 方法寫入給定值並返回偏移量加上寫入的位元組數。

示例

要建立緩衝區,我們將使用 NodeJS Buffer.alloc() 方法:

const buffer = Buffer.alloc(10);
buffer.writeFloatLE(0xfeaabe, 0);
console.log(buffer);

輸出

我們使用的偏移量是 0。執行時,從第 0 位開始的值將被寫入建立的緩衝區。上面建立的緩衝區長度為 10。因此,我們只能使用 0 到 6 之間的偏移量值。如果任何值 >6,它將引發錯誤 ERR_OUT_OF_RANGE

<Buffer be aa 7e 4b 00 00 00 00 00 00>

示例

在此示例中,我們將使用一個大於 buffer.length − 4 的偏移量。它應該丟擲如下所示的錯誤。

const buffer = Buffer.alloc(10);
buffer.writeFloatLE(0xfeaabe, 7);
console.log(buffer);

輸出

internal/buffer.js:83
   throw new ERR_OUT_OF_RANGE(type || 'offset',
   ^
   
RangeError [ERR_OUT_OF_RANGE]: The value of "offset" is out of range. It must be >= 0 and <= 6. Received 7
   at boundsError (internal/buffer.js:83:9)
   at checkBounds (internal/buffer.js:52:5)
   at Buffer.writeFloatForwards [as writeFloatLE] (internal/buffer.js:929:3)
   at Object.<anonymous> (C:\nodejsProject\src\testbuffer.js:2:8)
   at Module._compile (internal/modules/cjs/loader.js:1063:30)
   at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
   at Module.load (internal/modules/cjs/loader.js:928:32)
   at Function.Module._load (internal/modules/cjs/loader.js:769:14)
   at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
   at internal/main/run_main_module.js:17:47 {
      code: 'ERR_OUT_OF_RANGE'
   }

示例

要建立緩衝區,我們將使用 Buffer.allocUnsafe() 方法:

const buffer = Buffer.allocUnsafe(10);
buffer.writeFloatLE(0xfeaabe);
console.log(buffer);

輸出

未使用偏移量,預設情況下它將被視為 0。因此,上面的輸出如下所示。

<Buffer be aa 7e 4b 01 00 00 00 00 00>
nodejs_buffer_module.htm
廣告