0

I'm writing some code(javascript) to change a base 10 number into base 16. I know base 16 have letters if the remainder is between 10 and 15. This is where I am having trouble. I can't change the remainder into the letter.

so far this what I have:

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)

Let's say "mynum" = 4053 then I would get 5,13,15. But I want to get 5,D,F.I also tried using a "for" loop but got the same thing. It feels like i'm close but just missing something something, Can someone please help me?

mynum is the actual number, total is the remainder, and "remainder" is where i put the remainder's in a list

mplungjan
  • 169,008
  • 28
  • 173
  • 236

2 Answers2

4
hexString = yourNumber.toString(16);

it will convert base 10 to base 16

Himesh Suthar
  • 562
  • 4
  • 14
2

hexString = yourNumber.toString(16); is a better way to do it. But going by logic in your code, here is what you got wrong.

This remainder.push(total); statement should be after switch. In your code it is before 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);
vatz88
  • 2,422
  • 2
  • 14
  • 25