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

303
Visualizações
How to read a single bit from a Buffer in TypeScript?

I am aware that a similar question has already been asked before (see How to read a single bit buffer in node), but it seems none of the answers are helful. The first comment that has been accepted, stating to use buf.readUIntLE(), is not working since 2 arguments are expected, but 0 was provided.

Thus, I am currently trying to read a single bit (the 17th one) from a Buffer, but I can't find a way to easily read it. I have been using buffer.readUInt16BE(0) to read the 2 first bytes of the Buffer and so far it works fine, but I need to assign the 17th bit to a variable.

Note: My Buffer data is Big-Endian and I am coding in TypeScript.

I thought about doing something like:

const myVar: number = parseInt(buffer.readUIntBE(2, 1).toString().slice(0,1));

in order to read, then stringify the 3th byte, then getting the first caracter and convert it into a number, but I find it very clunky.

Is there a simple way to achieve this ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

A buffer is also a Uint8Array typed array, you can simply access its bytes by index. (If you prefer to do it with a method call, the equivalent would be readUint8). Then simply access the respective bit in that byte:

const position = 17;
const bitIndex = position & 7; // in byte
const byteIndex = position >> 3; // in buffer
const bit = (buffer[byteIndex] >> bitIndex) & 1

(Regarding the numbers: there are 8 = 2³ bits in a byte, and 7 is (1<<3)-1 or 0b111)

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