@ndn/util
Version:
NDNts: general utilities
52 lines (51 loc) • 1.54 kB
JavaScript
const INT2HEX = {};
for (let b = 0; b <= 0xFF; ++b) {
INT2HEX[b] = b.toString(16).padStart(2, "0").toUpperCase();
}
const HEX2INT = {};
for (let b = 0; b <= 0xF; ++b) {
const ch = b.toString(16);
HEX2INT[ch.toLowerCase()] = b;
HEX2INT[ch.toUpperCase()] = b;
}
/** Convert byte array to upper-case hexadecimal string. */
export function toHex(buf) {
let s = "";
for (const b of buf) {
s += INT2HEX[b];
}
return s;
}
(function (toHex) {
/** Conversion table from byte (0x00~0xFF) to upper-case hexadecimal. */
toHex.TABLE = INT2HEX;
})(toHex || (toHex = {}));
/**
* Convert hexadecimal string to byte array.
* @param s - Input hexadecimal string (case insensitive).
*
* @remarks
* The input is expected to be valid hexadecimal string.
* If the input is invalid, the output would be wrong, but no error would be thrown.
*/
export function fromHex(s) {
const b = new Uint8Array(s.length / 2);
for (let i = 0; i < b.length; ++i) {
b[i] = (HEX2INT[s[i * 2]] << 4) | HEX2INT[s[i * 2 + 1]];
}
return b;
}
(function (fromHex) {
/** Conversion table from hexadecimal digit (case insensitive) to nibble. */
fromHex.TABLE = HEX2INT;
})(fromHex || (fromHex = {}));
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
/** Convert string to UTF-8 byte array. */
export function toUtf8(s) {
return textEncoder.encode(s);
}
/** Convert UTF-8 byte array to string. */
export function fromUtf8(buf) {
return textDecoder.decode(buf);
}