• Node.js Video Tutorials

Node.js - Buffer.writeIntBE() 方法



NodeJS 的 Buffer.writeIntBE() 方法用於以大端位元組序的形式將指定長度的數值寫入緩衝區中給定偏移量的位置。

語法

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

buf.writeIntBE(value, offset, bytelength)

引數

此方法接受三個引數。具體說明如下。

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

  • offset − (必填) 指示寫入起始位置的偏移量。偏移量必須大於或等於 0,並且小於或等於 buffer.length-bytelength。預設值為 0。

  • byteLength − (必填) 要寫入的位元組數。byteLength 必須介於 0 到 6 之間。

返回值

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

示例

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

const buffer = Buffer.alloc(10);
buffer.writeIntBE(123, 0, 6);
console.log(buffer);

輸出

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

<Buffer 00 00 00 00 00 7b 00 00 00 00>

示例

在此示例中,我們將使用大於 6 的位元組長度。它應該丟擲如下所示的錯誤。

const buffer = Buffer.alloc(10);
buffer.writeIntBE(123, 0, 8);
console.log(buffer);

輸出

internal/buffer.js:83
   throw new ERR_OUT_OF_RANGE(type || 'offset',
   ^
   
RangeError [ERR_OUT_OF_RANGE]: The value of "byteLength" is out of range. It must be >= 1 and <= 6. Received 8
   at boundsError (internal/buffer.js:83:9)
   at Buffer.writeIntBE (internal/buffer.js:854: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.length − bytelength 的偏移量。

const buffer = Buffer.alloc(10);
buffer.writeIntBE(123, 8, 3);
console.log(buffer);

輸出

偏移量必須在 0 到 7 之間。由於我們使用了 8,它將丟擲如下所示的錯誤:

internal/buffer.js:83
   throw new ERR_OUT_OF_RANGE(type || 'offset',
   ^
   
RangeError [ERR_OUT_OF_RANGE]: The value of "byteLength" is out of range. It must be >= 1 and <= 6. Received 8
   at boundsError (internal/buffer.js:83:9)
PS C:\nodejsProject> node src/testbuffer.js
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 <= 7. Received 8
   at boundsError (internal/buffer.js:83:9)
   at checkBounds (internal/buffer.js:52:5)
   at checkInt (internal/buffer.js:71:3)
   at writeU_Int24BE (internal/buffer.js:817:3)
   at Buffer.writeIntBE (internal/buffer.js:875:12)
   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) {
      code: 'ERR_OUT_OF_RANGE'
   }
nodejs_buffer_module.htm
廣告

© . All rights reserved.