I need to convet from decimal to hexadecimal and keep the 0's
What I got i's
this.item = bytes[4].toString(16) + bytes[5].toString(16) + bytes[6].toString(16) + bytes[7].toString(16);
output:
79 2e 2 e1
i want:
79 2e 02 e1
So you want to pad leading 0s to every byte if it is below 10.
function toHex(bytes) {
return bytes.reduce(function(string, byte) {
return string + ("00" + byte.toString(16)).substr(-2);
}, '');
}
This Function lets u change your decimal to any new base between 2 and 36.
For Example 255 and 16 would return FF
fromDecToBase:function(int, toNewBase) {
var letters = ["0","1","2","3","4","5","6","7","8","9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
var returnValue= "";
if (toNewBase > 1 && toNewBase < 37) {
while(int != 0) {
rest = int % toNewBase;
int = Math.floor(int / toNewBase);
returnValue= letters[rest] + returnValue;
}
}
return returnValue;
},
All u need to do after it is check whether the string is 2 letters long or not which could be done the following way:
toHex:function(int)
{
hex = fromDecToBase(int, 16);
return hex.length == 1 ? "0"+hex:hex;
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With