5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Node.jsで16進数文字列を文字列に変換メモ

Last updated at Posted at 2020-09-16

Arduinoなどのマイコンボードなどのから情報送るときにたまに使うやつです。

Bufferでシンプルに書く

今のところこれがシンプルな感じです。 Bufferを使うのでNode.js環境のみですが

const string = Buffer.from(hexStr, 'hex').toString('utf-8');

これでOK。

実際に書くときはこんな感じです。

app.js
const hexStr = `48656c6c6f`; //16進数文字列
const string = Buffer.from(hexStr, 'hex').toString('utf-8');

console.log(string);

その他

  • もう少し丁寧に
const buf = Buffer.from(hexStr, 'hex'); //16進数文字列 -> Buffer
const string = buf.toString('utf-8'); //Buffer -> 文字列
  • バイト配列指定
const buf = new Buffer.from([0x48, 0x65, 0x6c, 0x6c, 0x6f]); //48656c6c6f
const string = buf.toString('utf-8');
  • ブラウザでも使える版
const string = (new TextDecoder).decode(Uint8Array.of(0x48, 0x65, 0x6c, 0x6c, 0x6f)); //48656c6c6f

ちなみに48656c6c6fは?

変換するとstringの値はHelloになります。

$ node app.js
Hello
5
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?