convert a number from base 10 to base 16 in typescript

To convert a number from base 10 to base 16 in TypeScript, you can use the toString() method with a radix of 16. Here's an example:

index.ts
const num: number = 255;
const hex: string = num.toString(16);

console.log(hex); // output: ff
96 chars
5 lines

In this example, num is the base 10 number that we want to convert to base 16. We then use the toString() method with a radix of 16 to convert it to hexadecimal. The resulting value is stored in hex, which is a string.

You can also use a custom function to perform the conversion manually, like this:

index.ts
function decToHex(num: number): string {
  const hexLookup: string[] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];

  let result: string = '';

  while (num > 0) {
    const digit: number = num % 16;
    result = hexLookup[digit] + result;
    num = Math.floor(num / 16);
  }

  return result;
}

const num: number = 255;
const hex: string = decToHex(num);

console.log(hex); // output: ff
428 chars
19 lines

In this example, decToHex() is a custom function that takes a base 10 number and returns a hexadecimal string. Inside the function, we use a lookup table (hexLookup) to convert each digit to its hexadecimal equivalent, then we iterate through the digits of the input number and append each hexadecimal digit to the result string (result). Finally, we return the result string, which contains the hexadecimal representation of the input number.

gistlibby LogSnag