Skip to content

Instantly share code, notes, and snippets.

@tauzen
Last active September 9, 2024 18:13
Show Gist options
  • Save tauzen/3d18825ae41ff3fc8981 to your computer and use it in GitHub Desktop.
Save tauzen/3d18825ae41ff3fc8981 to your computer and use it in GitHub Desktop.
Hex string to byte and other way round conversion functions.
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
Copy link

cprcrack commented Jun 1, 2018

Assuming the input is always a Uint8Array, what is the use of & 0xff in line 8?

@dbeckwith01
Copy link

@cprcrack The intent of & 0xff is to ensure the value fits in 8-bits, a number between 0 and 255.

@nikitakoliadin
Copy link

Thx)))

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