2022-03-25 03:32:07 +00:00
|
|
|
import { fromString } from "uint8arrays/from-string";
|
|
|
|
import { toString } from "uint8arrays/to-string";
|
2022-01-13 00:33:26 +00:00
|
|
|
|
2022-02-13 23:50:02 +00:00
|
|
|
/**
|
|
|
|
* Convert input to a byte array.
|
2022-03-25 03:32:07 +00:00
|
|
|
*
|
|
|
|
* Handles both `0x` prefixed and non-prefixed strings.
|
2022-02-13 23:50:02 +00:00
|
|
|
*/
|
|
|
|
export function hexToBytes(hex: string | Uint8Array): Uint8Array {
|
|
|
|
if (typeof hex === "string") {
|
|
|
|
const _hex = hex.replace(/^0x/i, "");
|
2022-03-25 03:32:07 +00:00
|
|
|
return fromString(_hex, "base16");
|
2022-02-13 23:50:02 +00:00
|
|
|
}
|
|
|
|
return hex;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Convert byte array to hex string (no `0x` prefix).
|
|
|
|
*/
|
2022-03-25 03:32:07 +00:00
|
|
|
export const bytesToHex = (bytes: Uint8Array): string =>
|
|
|
|
toString(bytes, "base16");
|
2022-02-13 23:50:02 +00:00
|
|
|
|
2022-03-25 05:20:14 +00:00
|
|
|
/**
|
|
|
|
* Decode byte array to utf-8 string.
|
|
|
|
*/
|
|
|
|
export const bytesToUtf8 = (b: Uint8Array): string => toString(b, "utf8");
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Encode utf-8 string to byte array.
|
|
|
|
*/
|
|
|
|
export const utf8ToBytes = (s: string): Uint8Array => fromString(s, "utf8");
|