Last active
September 9, 2024 18:13
-
-
Save tauzen/3d18825ae41ff3fc8981 to your computer and use it in GitHub Desktop.
Hex string to byte and other way round conversion functions.
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
function byteToHexString(uint8arr) { | |
if (!uint8arr) { | |
return ''; | |
} | |
var hexStr = ''; | |
for (var i = 0; i < uint8arr.length; i++) { | |
var hex = (uint8arr[i] & 0xff).toString(16); | |
hex = (hex.length === 1) ? '0' + hex : hex; | |
hexStr += hex; | |
} | |
return hexStr.toUpperCase(); | |
} | |
function hexStringToByte(str) { | |
if (!str) { | |
return new Uint8Array(); | |
} | |
var a = []; | |
for (var i = 0, len = str.length; i < len; i+=2) { | |
a.push(parseInt(str.substr(i,2),16)); | |
} | |
return new Uint8Array(a); | |
} |
@cprcrack The intent of & 0xff
is to ensure the value fits in 8-bits, a number between 0 and 255.
Thx)))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Assuming the input is always a Uint8Array, what is the use of
& 0xff
in line 8?