Created
August 21, 2022 22:04
-
-
Save markodayan/35745db7f82ca39c5effefa4cca81fb6 to your computer and use it in GitHub Desktop.
Encoding Helpers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* If string supplied is prefixed with '0x' remove it and return the new string */ | |
function stripHexPrefix(input: string): string { | |
if (input.startsWith('0x')) { | |
input = input.slice(2); | |
} | |
return input; | |
} | |
/* Convert a hexadecimal string to an array of hexadecimal byte values (in preparation of inserting into a byte array) */ | |
function hexStringToByteArr(input: string): Uint8Array { | |
input = stripHexPrefix(input); | |
let arr: string[] = []; | |
if (input.length % 2 === 0) { | |
// if even number of hex digits -> input doesn't require prefixing for splitting into hex byte values | |
arr = input.match(/.{1,2}/g)! as string[]; | |
} else { | |
// if odd number of hex digits -> prefix with 0 digit before splitting into hex byte values | |
arr = ('0' + input).match(/.{1,2}/g)! as string[]; | |
} | |
// Convert hexadecimal value array to decimal value array | |
const decimalArr = arr.map((h) => parseInt(h, 16)); | |
// Create byte array from decimal value array | |
return Uint8Array.from(decimalArr); | |
} | |
/** Method to detect whether input is escaped hexadecimal sequence */ | |
function isEscapedFormat(input: Input): boolean { | |
if (typeof input === 'string') { | |
return encodeURI(input[0]).startsWith('%'); | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment