47 lines
1.4 KiB
JavaScript
47 lines
1.4 KiB
JavaScript
/**
|
|
* Utility object for handling hexadecimal and binary data conversions.
|
|
* @namespace
|
|
*/
|
|
export const HexMix = {
|
|
/**
|
|
* Converts a Uint8Array to a hexadecimal string.
|
|
* @param {Uint8Array} data - The input Uint8Array.
|
|
* @returns {string} The hexadecimal representation of the input data.
|
|
*/
|
|
uint8ToHex(data) {
|
|
return Array.from(data, (byte) => ("00" + byte.toString(16)).slice(-2)).join("");
|
|
},
|
|
|
|
/**
|
|
* Converts a hexadecimal string to a Uint8Array.
|
|
* @param {string} data - The input hexadecimal string.
|
|
* @returns {Uint8Array} The Uint8Array representation of the input data.
|
|
*/
|
|
hexToUint8(data) {
|
|
const hexArray = data.match(/.{1,2}/g);
|
|
return hexArray ? new Uint8Array(hexArray.map((char) => parseInt(char, 16))) : new Uint8Array(0);
|
|
},
|
|
|
|
/**
|
|
* Converts an ArrayBuffer to a Base64 string.
|
|
* @param {ArrayBuffer} buf - The input ArrayBuffer.
|
|
* @returns {string} The Base64 representation of the input data.
|
|
*/
|
|
arrayBufferToBase64(buf) {
|
|
return btoa(String.fromCharCode.apply(null, new Uint8Array(buf)));
|
|
},
|
|
|
|
/**
|
|
* Converts a string to an ArrayBuffer.
|
|
* @param {string} str - The input string.
|
|
* @returns {ArrayBuffer} The ArrayBuffer representation of the input string.
|
|
*/
|
|
stringToArrayBuffer(str) {
|
|
const array = new Uint8Array(str.length);
|
|
for (let i = 0; i < str.length; i++) {
|
|
array[i] = str.charCodeAt(i);
|
|
}
|
|
return array.buffer;
|
|
}
|
|
};
|