Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat/node: Add hex-byte util fns #1390

Merged
merged 3 commits into from
Oct 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions bindings/nodejs/lib/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,34 @@
export * from './utf8';
export * from './utils';
export * from '../types/utils';

/**
* Converts a byte array to a hexadecimal string.
*
* @param {Uint8Array} byteArray - The bytes to encode.
* @param {boolean} [prefix=false] - Whether to include the '0x' prefix in the resulting hexadecimal string.
* @returns {string} The hexadecimal representation of the input byte array.
*/
export const bytesToHex = (bytes: ArrayLike<number>, prefix = false) => {
Thoralf-M marked this conversation as resolved.
Show resolved Hide resolved
const hexArray = Array.from(bytes, (byte) =>
byte.toString(16).padStart(2, '0'),
);
const hexString = hexArray.join('');
return prefix ? '0x' + hexString : hexString;
};

/**
* Converts a hexadecimal string to a Uint8Array byte array.
*
* @param {string} hexString - The hexadecimal string to be converted.
* @returns {Uint8Array} The Uint8Array byte array representation of the input hexadecimal string.
* @throws {Error} Will throw an error if the input string is not a valid hexadecimal string.
*/
export const hexToBytes = (hexString: string) => {
const hex = hexString.replace(/^0x/, '');
DaughterOfMars marked this conversation as resolved.
Show resolved Hide resolved
const bytes = [];
for (let i = 0; i < hex.length; i += 2) {
bytes.push(parseInt(hex.substr(i, 2), 16));
}
return new Uint8Array(bytes);
};
2 changes: 1 addition & 1 deletion bindings/nodejs/lib/utils/utf8.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const utf8ToBytes = (utf8: string) => {

/** Convert hex encoded string to UTF8 string */
export const hexToUtf8 = (hex: HexEncodedString) =>
decodeURIComponent(hex.replace('0x', '').replace(/[0-9a-f]{2}/g, '%$&'));
decodeURIComponent(hex.replace(/^0x/, '').replace(/[0-9a-f]{2}/g, '%$&'));
thibault-martinez marked this conversation as resolved.
Show resolved Hide resolved

/** Convert UTF8 string to hex encoded string */
export const utf8ToHex = (utf8: string) =>
Expand Down