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

213
Visualizações
Extraneous character while converting string to buffer and back in javascript

In node v16.14.2,

> String.fromCharCode.apply(null, Buffer.from('°'))
'°'

This works fine though:

> Buffer.from('°').toString('utf-8')
'°'

I want to know why the first scenario adds an extra character in the output.

Browser example:

console.log(String.fromCharCode.apply(null, ethereumjs.Buffer.Buffer.from('°'))) /// '°'
console.log(ethereumjs.Buffer.Buffer.from('°').toString('utf-8')) // '°'
console.log(new Uint8Array(ethereumjs.Buffer.Buffer.from('°'))) // [ 194, 176 ]
console.log(new Uint8Array(ethereumjs.Buffer.Buffer.from(String.fromCharCode(176)))) // [ 194, 176 ]
<script src="https://cdn.jsdelivr.net/gh/ethereumjs/browser-builds/dist/ethereumjs-tx/ethereumjs-tx-1.3.3.min.js"></script>

EDIT: Another funny thing:

> new Uint8Array(Buffer.from('°'))
Uint8Array(2) [ 194, 176 ]
> new Uint8Array(Buffer.from(String.fromCharCode(176)))
Uint8Array(2) [ 194, 176 ]
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The default string encoding of Buffer.from is UTF-8 which encodes characters in the Extended ASCII range using two bytes. (It can't just use one byte because the highest order bit of that byte is used to signal multibyte encoding.)

UTF-8 two-byte encoding has the form:

110xxxxx 10xxxxxx

which gives 11 bits to represent a character code.

The ASCII code of '°' is 176

> '°'.charCodeAt(0)
176

which in binary is:

> (176).toString(2)
'10110000'

So replacing the x with this binary value we have:

110xxxxx 10xxxxxx
110xxx10 10110000
      ^^   ^^^^^^

which means the UTF-8 two-byte encoding of '°' is

11000010 10110000

or

194 176

as expected:

> [...Buffer.from('°')]
[ 194, 176 ]

> String.fromCharCode(194)
'Â'

> String.fromCharCode(176)
'°'
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