Reputation: 167
I want to convert an hex number (let's say 0xABCDEF) into an array (0xABCDEF --> [0xAB;0xCD;0xEF]
I have tested this code:
generateHexaArrayOf2FromHexaNumber (hexaNb){
var size = 1;
var hexaNbTempo = hexaNb;
while ((hexaNbTempo / 0xFF) > 1) {
hexaNbTempo = hexaNbTempo / 0xFF;
size++;
}
var hexaArray = new Array(size);
for (var i= 0; hexaNb > 0; i++) {
hexaArray[i] = hexaNb % 0xFF
hexaNb = Math.floor(hexaNb / 0xFF) // round to lower
}
hexaArray.reverse();
return hexaArray;
}
Result is returned in ASCII not in hexa (have With 0xABCDEF as an entry it returns [173(=0xAD), 39(=0x27), 105(=0x69)]
Do you know why it is wrong and how to correct it ?
Upvotes: 0
Views: 69
Reputation: 19475
Replace all 0xFF
by 0x100
. After all, you’re trying to make a base-256 array, not a base-255 one.
Also, you really don’t need the size
calculation. You can also return hexaArray.reverse()
directly. Also, use push
instead of direct property assignment. Your code also left the array empty for input 0
, but wouldn’t you expect [0]
as output?
Instead of .push
you could also use .unshift
and remove .reverse()
.
Corrected code:
function generateHexaArrayOf2FromHexaNumber(hexaNb) {
var hexaArray = [];
for (var i = 0; hexaNb > 0; i++) {
hexaArray.push(hexaNb % 0x100);
hexaNb = Math.floor(hexaNb / 0x100);
}
if(!hexaArray.length){
hexaArray.push(0);
}
return hexaArray.reverse();
}
console.log(generateHexaArrayOf2FromHexaNumber(0x1)); // => [ 1 ]
console.log(generateHexaArrayOf2FromHexaNumber(0xabcdef)); // => [ 171, 205, 239 ]
console.log(generateHexaArrayOf2FromHexaNumber(0xabcdef).map((x) => x.toString(16).padStart(2, "0"))); // => [ "ab", "cd", "ef" ]
console.log(generateHexaArrayOf2FromHexaNumber(0xdeadbeef).map((x) => x.toString(16).padStart(2, "0"))); // => [ "de", "ad", "be", "ef" ]
console.log(generateHexaArrayOf2FromHexaNumber(0x0).map((x) => x.toString(16).padStart(2, "0"))); // => [ "00" ]
Upvotes: 1