Last active
February 18, 2017 02:43
-
-
Save roycrxtw/e07e4f705dd09608fabc287f08a4dbc4 to your computer and use it in GitHub Desktop.
Convert array to Hex String
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
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