Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

312
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda