Skip to content

Commit 9943e36

Browse files
feat: add decimal to hexadecimal conversion
1 parent 5c39e87 commit 9943e36

2 files changed

Lines changed: 71 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* @function decimalToHexadecimal
3+
* @description Converts a decimal number (base-10) to its hexadecimal
4+
* (base-16) string representation without using JavaScript's
5+
* built-in toString(16).
6+
* @param {number} decimal - A non-negative integer
7+
* @returns {string} - The hexadecimal string representation in uppercase
8+
* @see https://en.wikipedia.org/wiki/Hexadecimal
9+
* @example decimalToHexadecimal(255) => "FF"
10+
* @example decimalToHexadecimal(16) => "10"
11+
* @example decimalToHexadecimal(0) => "0"
12+
*/
13+
const decimalToHexadecimal = (decimal) => {
14+
if (!Number.isInteger(decimal) || decimal < 0) {
15+
throw new TypeError('Input must be a non-negative integer')
16+
}
17+
if (decimal === 0) return '0'
18+
const hexChars = '0123456789ABCDEF'
19+
let hex = ''
20+
let num = decimal
21+
while (num > 0) {
22+
hex = hexChars[num % 16] + hex
23+
num = Math.floor(num / 16)
24+
}
25+
return hex
26+
}
27+
28+
export { decimalToHexadecimal }
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { decimalToHexadecimal } from '../DecimalToHexadecimal.js'
2+
3+
describe('decimalToHexadecimal', () => {
4+
test("decimalToHexadecimal(0) returns '0'", () => {
5+
expect(decimalToHexadecimal(0)).toBe('0')
6+
})
7+
8+
test("decimalToHexadecimal(10) returns 'A'", () => {
9+
expect(decimalToHexadecimal(10)).toBe('A')
10+
})
11+
12+
test("decimalToHexadecimal(15) returns 'F'", () => {
13+
expect(decimalToHexadecimal(15)).toBe('F')
14+
})
15+
16+
test("decimalToHexadecimal(16) returns '10'", () => {
17+
expect(decimalToHexadecimal(16)).toBe('10')
18+
})
19+
20+
test("decimalToHexadecimal(255) returns 'FF'", () => {
21+
expect(decimalToHexadecimal(255)).toBe('FF')
22+
})
23+
24+
test("decimalToHexadecimal(256) returns '100'", () => {
25+
expect(decimalToHexadecimal(256)).toBe('100')
26+
})
27+
28+
test("decimalToHexadecimal(4096) returns '1000'", () => {
29+
expect(decimalToHexadecimal(4096)).toBe('1000')
30+
})
31+
32+
test('throws TypeError for negative input', () => {
33+
expect(() => decimalToHexadecimal(-1)).toThrow(TypeError)
34+
})
35+
36+
test('throws TypeError for float input', () => {
37+
expect(() => decimalToHexadecimal(1.5)).toThrow(TypeError)
38+
})
39+
40+
test('throws TypeError for non-number input', () => {
41+
expect(() => decimalToHexadecimal('FF')).toThrow(TypeError)
42+
})
43+
})

0 commit comments

Comments
 (0)