I want to change base 10 number to base 16
本问题已经有最佳答案,请猛点这里访问。
我正在编写一些代码(javascript)将基数10改为基数16。我知道以16为底的有字母,如果余数在10到15之间。这就是我遇到麻烦的地方。我不能把剩下的改成信。
到目前为止,我有:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | 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) |
假设"mynum"=4053,那么我得到5,13,15。但我想得到5,d,f。我也试过使用"for"循环,但得到了相同的结果。感觉我很亲近,但我错过了什么,有人能帮我吗?
mynum是实际的数字,total是余数,"余数"是我将余数放在列表中的位置。
1 | hexString = yourNumber.toString(16); |
它将以10为基数转换为以16为基数
此
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | 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); |