Arduinoなどのマイコンボードなどのから情報送るときにたまに使うやつです。
Bufferでシンプルに書く
今のところこれがシンプルな感じです。 Bufferを使うのでNode.js環境のみですが
conststring=Buffer.from(str,'hex').toString('utf-8');これでOK。
実際に書くときはこんな感じです。
app.js
conststr=`48656c6c6f`;//16進数文字列conststring=Buffer.from(str,'hex').toString('utf-8');console.log(string);その他
- もう少し丁寧に
constbuf=Buffer.from(str,'hex');//16進数文字列 -> Bufferconststring=buf.toString('utf-8');//Buffer -> 文字列- バイト配列指定
constbuf=newBuffer.from([0x48,0x65,0x6c,0x6c,0x6f]);//48656c6c6fconststring=buf.toString('utf-8');- ブラウザでも使える版
conststring=(newTextDecoder).decode(Uint8Array.of(0x48,0x65,0x6c,0x6c,0x6f));ちなみに
実行すると全てstringの値はHelloになります。
$ node app.js
Hello