Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@cprcrack cprcrack commented Jun 1, 2018

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

@dbeckwith01

This comment has been minimized.

Copy link

@dbeckwith01 dbeckwith01 commented Jun 22, 2018

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

@nikitakoliadin

This comment has been minimized.

Copy link

@nikitakoliadin nikitakoliadin commented Feb 8, 2019

Thx)))

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