iTranslated by AI
Converting between Buffer and floats, integers, and other encodings in JavaScript
I have summarized how to convert between Buffer and other types in JavaScript.
I have also published a REPL.
Repl.it - buffer
Number → Buffer
Numbers are converted in the sequence of → Typed Array → Buffer.
// int → Buffer
const intBuf = Buffer.from(new Uint8Array([120]).buffer)
// float → Buffer
const floatBuf = Buffer.from(new Float32Array([1.23]).buffer)
// double → Buffer
const doubleBuf = Buffer.from(new Float64Array([1.2345]).buffer)
Buffer → Number
// Buffer → int
const int = intBuf.readInt8(0)
// Buffer → float
const float = floatBuf.readFloatLE(0)
// Buffer → double
const double = doubleBuf.readDoubleLE(0)
// { int: 120, float: 1.2300000190734863, double: 1.2345 }
String ↔ Buffer
This is the simplest.
// string → Buffer
const strBuf = Buffer.from('かぼちゃ')
// <Buffer e3 81 8b e3 81 bc e3 81 a1 e3 82 83>
// Buffer → string
strBuf.toString()
// かぼちゃ
Other Encodings ↔ Buffer
// "かぼちゃ" Buffer → Each encoding
strBuf.toString('hex')
// e3818be381bce381a1e38283
strBuf.toString('base64')
// 44GL44G844Gh44KD
strBuf.toString('utf8')
// かぼちゃ
strBuf.toString('utf16le')
// 臣벁臣莂
// Each encoding → Buffer
Buffer.from('e3818be381bce381a1e38283', 'hex')
Buffer.from('44GL44G844Gh44KD', 'base64')
Buffer.from('かぼちゃ', 'utf8')
Buffer.from('臣벁臣莂', 'utf16le')
// <Buffer e3 81 8b e3 81 bc e3 81 a1 e3 82 83>
About Other Numeric Types
Besides Uint8 and Float32 shown in the examples, there are various other types categorized by "size (number of bytes)" and "signedness."
Please use the one that is most appropriate for your needs.
from buffer
Buffer | Node.js v15.0.1 Documentation
to buffer
JavaScript Typed Arrays - JavaScript | MDN
Conversion Examples
An example of converting a base64 encoded string back to Double.
(base64 ↔ Buffer ↔ Double)
Buffer.from(new Float64Array([321.123]).buffer).toString('base64')
// 'hxbZzvcRdEA='
Buffer.from('hxbZzvcRdEA=', 'base64').readDoubleLE()
// 321.123
Converting hex encoding back to int.
(hex ↔ Buffer ↔ int)
Buffer.from(new Int32Array([20201010]).buffer).toString('hex')
// '323e3401'
Buffer.from('323e3401', 'hex').readInt32LE(0)
// 20201010
If the range is incorrect, you will get a different value
Naturally, if you use a different read type than the format you wrote in, the value will be different.
const b1 = Buffer.from(new Uint32Array([1234]).buffer)
b1.readInt32LE(0)
// o 1234
b1.readInt32BE(0)
// x -771489792 Endian mismatch
b1.readInt8(0)
// x -46 Byte length mismatch
The same applies if the range of the value during conversion is incorrect.
const b2 = Buffer.from(new Uint8Array([-10]).buffer)
// Range error: Negative value despite being Unsigned
b2.readUInt8(0)
// x 246
const b3 = Buffer.from(new Uint16Array([65536]).buffer)
// Range error: Value greater than 65535
b3.readUInt16LE(0)
// x 0
Discussion