Lee
Lee

Reputation: 31040

Pad nodejs buffer to 32 bytes after creation from string

Say I create a buffer from a string:

let buf = Buffer.from('a test');

What is a good way to pad buf (with zeros or nulls) to 32 bytes?

Upvotes: 1

Views: 2863

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

I can think of a couple of options:

Pad first

You could pad the string before using from:

const buf = Buffer.from(theString.padEnd(32, "\0"));

Note that if the string's length is greater than 32, the buffer's will be as well.

If theString is "example" (for instance), you end up with these bytes in the buffer:

65 78 61 6d 70 6c 65 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

alloc and copy

Alternatively, alloc and copy:

const buf = Buffer.alloc(32, 0);
Buffer.from(theString).copy(buf);

Note that only as many bytes as will fit are copied (it doesn't throw if the string is longer, it just leaves off the end).

Upvotes: 3

Terry Lennox
Terry Lennox

Reputation: 30685

You can also use Buffer.concat() for this purpose:

let buf =  Buffer.from('a test');

const totalLength = 32;
const result = Buffer.concat([buf], totalLength);

console.log('Result length:', result.length);
console.log('Result:', result);

This will output something like:

Result length: 32

Result: <Buffer 61 20 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00>

Upvotes: 3

Related Questions