2024-02-28 16:49:44 +00:00
|
|
|
export const shorten = (str: string, offset = 9) => {
|
|
|
|
// return original string if it is not long enough
|
|
|
|
if (str.length < offset * 2 + 4) return str
|
|
|
|
|
|
|
|
return `${str.slice(0, offset)}...${str.slice(
|
|
|
|
str.length - offset,
|
|
|
|
str.length
|
|
|
|
)}`
|
|
|
|
}
|
2024-04-08 12:45:51 +00:00
|
|
|
|
|
|
|
export const stringToHex = (str: string) => {
|
|
|
|
// Convert the string to an array of UTF-16 code units using the spread operator
|
|
|
|
const codeUnits = [...str]
|
|
|
|
|
|
|
|
// Map each code unit to its hexadecimal representation
|
|
|
|
const hexChars = codeUnits.map((codeUnit) => {
|
|
|
|
// Convert the code unit to its hexadecimal representation with leading zeros
|
|
|
|
const hex = codeUnit.charCodeAt(0).toString(16).padStart(2, '0')
|
|
|
|
return hex
|
|
|
|
})
|
|
|
|
|
|
|
|
// Join the hexadecimal characters into a single string
|
|
|
|
const hexString = hexChars.join('')
|
|
|
|
|
|
|
|
// Return the resulting hexadecimal string
|
|
|
|
return hexString
|
|
|
|
}
|
|
|
|
|
|
|
|
export const hexToString = (hex: string) => {
|
|
|
|
// Split the hex string into pairs of two characters
|
|
|
|
const pairs = hex.match(/.{1,2}/g) || []
|
|
|
|
|
|
|
|
// Convert each pair from hexadecimal to its decimal equivalent,
|
|
|
|
// then convert each decimal value to its character representation
|
|
|
|
const chars = pairs.map((pair) => String.fromCharCode(parseInt(pair, 16)))
|
|
|
|
|
|
|
|
// Join the resulting characters into a single string
|
|
|
|
return chars.join('')
|
|
|
|
}
|
2024-04-16 08:29:56 +00:00
|
|
|
|
|
|
|
// Function to convert a Uint8Array to a hexadecimal string
|
|
|
|
export const uint8ArrayToHexString = (uint8Array: Uint8Array) => {
|
|
|
|
// Convert each byte in the Uint8Array to a hexadecimal string,
|
|
|
|
// pad it with leading zeros if necessary, and join the results
|
|
|
|
return Array.from(uint8Array)
|
|
|
|
.map((byte) => byte.toString(16).padStart(2, '0')) // Convert byte to hexadecimal string
|
|
|
|
.join('') // Join all hexadecimal strings
|
|
|
|
}
|
|
|
|
|
|
|
|
// Function to convert a hexadecimal string to a Uint8Array
|
|
|
|
export const hexStringToUint8Array = (hexString: string) => {
|
|
|
|
// Create a new Uint8Array with half the length of the hex string
|
|
|
|
const uint8Array = new Uint8Array(hexString.length / 2)
|
|
|
|
// Iterate over pairs of characters in the hex string
|
|
|
|
for (let i = 0; i < hexString.length; i += 2) {
|
|
|
|
// Parse the pair of characters as a hexadecimal value and store it in the Uint8Array
|
|
|
|
uint8Array[i / 2] = parseInt(hexString.substr(i, 2), 16)
|
|
|
|
}
|
|
|
|
// Return the resulting Uint8Array
|
|
|
|
return uint8Array
|
|
|
|
}
|