Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

311
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda