NodeJS Buffer.writeUInt32BE() 方法有助于在给定偏移量处以大端形式将无符号 32 位值写入缓冲区。如果值不是 32 位无符号整数,则返回 undefined。
语法
以下是Node.JS Buffer.writeUInt32BE()方法的语法 -
buf.writeUInt32BE(value[, offset])
参数
此方法接受两个参数。下面将对此进行解释。
- value − (必需)要写入缓冲区的无符号 32 位数字。
- offset - 指示开始写入的位置的偏移量。偏移量大于或等于 0,也小于或等于 buffer.length-4。默认值为 0。
返回值
buffer.writeUInt32BE() 方法写入给定值并返回偏移量加上写入的字节数。
例为了创建一个缓冲区,我们将使用 NodeJS Buffer.alloc() 方法 -
const buffer = Buffer.alloc(10);
buffer.writeUInt32BE(1000);
console.log(buffer);
输出
在执行时,从第 0 个位置开始的值将被写入创建的缓冲区。为上述创建的缓冲区长度为 10。因此,我们只能使用值为 0 到 6 的偏移量。如果任何值 >6,它将给出错误 ERR_OUT_OF_RANGE。
<Buffer e8 03 00 00 00 00 00 00 00 00>
例
在此示例中,将使用缓冲区长度为 5 和偏移量大于 buffer.length −4 。
const buffer = Buffer.alloc(5);
buffer.writeUInt32BE(1000, 2);
console.log(buffer);
输出
internal/buffer.js:58
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 <= 1. Received 2
at boundsError (internal/buffer.js:58:9)
at checkBounds (internal/buffer.js:39:5)
at checkInt (internal/buffer.js:46:3)
at writeU_Int32BE (internal/buffer.js:636:3)
at Buffer.writeUInt32BE (internal/buffer.js:649:10)
at Object.<anonymous> (C:\nodejsProject\src\testbuffer.js:2:8)
at Module._compile (internal/modules/cjs/loader.js:816:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
at Module.load (internal/modules/cjs/loader.js:685:32)
at Function.Module._load (internal/modules/cjs/loader.js:620:12)
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 <= 1. Received 2
at boundsError (internal/buffer.js:58:9)
at checkBounds (internal/buffer.js:39:5)
at checkInt (internal/buffer.js:46:3)
at writeU_Int32BE (internal/buffer.js:636:3)
at Buffer.writeUInt32BE (internal/buffer.js:649:10)
at Object.<anonymous> (C:\nodejsProject\src\testbuffer.js:2:8)
at Module._compile (internal/modules/cjs/loader.js:816:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
at Module.load (internal/modules/cjs/loader.js:685:32)
at Function.Module._load (internal/modules/cjs/loader.js:620:12)
例
在此示例中,将创建一个缓冲区,并从范围内的偏移量写入。
const buffer = Buffer.alloc(10);
buffer.writeUInt32BE(123, 4);
console.log(buffer);
输出
偏移量必须介于 0 到 6 之间。上述代码的输出在执行时如下所示 -
<Buffer 00 00 00 00 00 00 00 7b 00 00>