我正在编写一些代码(javascript)来将基数10改为基数16.我知道如果剩下的数字在10到15之间,则基数16会有字母。这就是我遇到麻烦的地方。我无法将剩余部分改为字母。
到目前为止,我所拥有的是:
var mynum = 4053,remainder=[];
while (mynum > 0) {
total = mynum % 16;
remainder.push(total);
mynum = Math.floor(mynum / 16);
switch (total > 9 || total < 16) {
case total === 10:
total = "A";
break;
case total === 11:
total = "B";
break;
case total === 12:
total = "C";
break;
case total === 13:
total = "D";
break;
case total === 14:
total = "E";
break;
case total === 15:
total = "F";
break;
}
}
console.log(total,remainder)
&#13;
让我们说&#34; mynum&#34; = 4053然后我会得到5,13,15。但是我想得到5,D,F.我也尝试使用&#34; for&#34;循环,但得到了相同的东西。感觉就像我关闭但只是遗漏了某些东西,有人可以帮助我吗?
mynum是实际数字,总数是余数,&#34;余数&#34;是我把剩余部分放在列表中的地方
答案 0 :(得分:2)
hexString = yourNumber.toString(16);
是一种更好的方法。但是按照你的代码中的逻辑,这就是你错了。
此remainder.push(total);
语句应在switch
之后。在您的代码中,它位于switch
之前。
mynum = 4053;
remainder = [];
while ( mynum > 0){
total = mynum % 16;
mynum = Math.floor(mynum / 16);
// remainder.push(total);
switch (total > 9 || total < 16){
case total === 10:
total = "A";
break;
case total === 11:
total = "B";
break;
case total === 12:
total = "C";
break;
case total === 13:
total = "D";
break;
case total === 14:
total = "E";
break;
case total === 15:
total = "F";
break;
}
remainder.push(total); // here
}
console.log(remainder);
答案 1 :(得分:2)
hexString = yourNumber.toString(16);
它会将基数10转换为基数16