文字列またはTypedArrayを16進数の文字列に変換する
デバッグ用。スペース区切りの16進表記にする。
もくじ
文字列→16進数の文字列
split()
で配列にする → map()
で各要素に charCodeAt(0)
して数値 (UTF-16コード、0~65535) に変換 → 数値に toString(16)
で16進表記の文字列に変換 → join()
で結合。
const hexStr = 'ABCDかきくけ'.split('').map(v => v.charCodeAt(0).toString(16)).join(' ');
console.log(hexStr);
// -> 41 42 43 44 304b 304d 304f 3051
TypedArray|Buffer →16進数の文字列
reduce()
で各要素を toString(16)
しながら結合。
// Uint16Array生成
const uint16Array = Uint16Array.from('ABCDかきくけ'.split('').map(v => v.charCodeAt(0)));
// 16進数の文字列に変換
const hexStr = uint16Array.reduce((a, c) => a + (a === '' ? '' : ' ') + c.toString(16), '');
console.log(hexStr);
// -> 41 42 43 44 304b 304d 304f 3051
TypedArray
は map
だとうまくいかない。map
で生成される配列自体が TypedArray
だから、16進表記でA~Eが出現したときに結果がおかしくなる。