Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@roycrxtw
Last active February 18, 2017 02:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roycrxtw/e07e4f705dd09608fabc287f08a4dbc4 to your computer and use it in GitHub Desktop.
Save roycrxtw/e07e4f705dd09608fabc287f08a4dbc4 to your computer and use it in GitHub Desktop.
Convert array to Hex String
var arr = [127, 1128, 5, 31];
function toHexString(array){
var result = [];
for(var i in array){
// directly toString()
result.push(array[i].toString(16));
}
return result;
}
function toHexStringWithPadding(array, len){
var result = [];
var str = "";
for(var i in array){
// Add correct number of leading zeros before toString str,
// this will format the result to specific(len arg) chars correctly.
str = array[i].toString(16);
result.push( "0".repeat(len - str.length) + str);
}
return result;
}
console.log("Compare the results from this two functions:");
console.log(toHexString(arr));
console.log(toHexStringWithPadding(arr, 4));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment