Created
February 11, 2020 19:16
-
-
Save llzes/7e0a324239653f32f8eb78a09208de52 to your computer and use it in GitHub Desktop.
Byte to Hex and Hex to Byte in JavaScript.
This file contains 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
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' |
This file contains 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
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] |
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
Thank you, your code has helped me with one of my projects! 😉