Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

310
Views
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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).

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!