Skip to content

Instantly share code, notes, and snippets.

@llzes
Created February 11, 2020 19:16
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save llzes/7e0a324239653f32f8eb78a09208de52 to your computer and use it in GitHub Desktop.
Save llzes/7e0a324239653f32f8eb78a09208de52 to your computer and use it in GitHub Desktop.
Byte to Hex and Hex to Byte in JavaScript.
const byteToHex = (byte) => {
const key = '0123456789abcdef'
let bytes = new Uint8Array(byte)
let newHex = ''
let currentChar = 0
for (let i=0; i<bytes.length; i++) { // Go over each 8-bit byte
currentChar = (bytes[i] >> 4) // First 4-bits for first hex char
newHex += key[currentChar] // Add first hex char to string
currentChar = (bytes[i] & 15) // Erase first 4-bits, get last 4-bits for second hex char
newHex += key[currentChar] // Add second hex char to string
}
return newHex
}
// byteToHex([104,101,108,108,111])
// => '68656c6c6f'
const hexToByte = (hex) => {
const key = '0123456789abcdef'
let newBytes = []
let currentChar = 0
let currentByte = 0
for (let i=0; i<hex.length; i++) { // Go over two 4-bit hex chars to convert into one 8-bit byte
currentChar = key.indexOf(hex[i])
if (i%2===0) { // First hex char
currentByte = (currentChar << 4) // Get 4-bits from first hex char
}
if (i%2===1) { // Second hex char
currentByte += (currentChar) // Concat 4-bits from second hex char
newBytes.push(currentByte) // Add byte
}
}
return new Uint8Array(newBytes)
}
// hexToByte('68656c6c6f')
// => [104, 101, 108, 108, 111]
@nadiemedicejose
Copy link

Thank you, your code has helped me with one of my projects! 😉

@AlbertXiaoPeng
Copy link

Thank you, your code has helped me with one of my projects! 😉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment