Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Conversions/DecimalToHexadecimal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* @function decimalToHexadecimal
* @description Converts a decimal number (base-10) to its hexadecimal
* (base-16) string representation without using JavaScript's
* built-in toString(16).
* @param {number} decimal - A non-negative integer
* @returns {string} - The hexadecimal string representation in uppercase
* @see https://en.wikipedia.org/wiki/Hexadecimal
* @example decimalToHexadecimal(255) => "FF"
* @example decimalToHexadecimal(16) => "10"
* @example decimalToHexadecimal(0) => "0"
*/
const decimalToHexadecimal = (decimal) => {
if (!Number.isInteger(decimal) || decimal < 0) {
throw new TypeError('Input must be a non-negative integer')
}
if (decimal === 0) return '0'
const hexChars = '0123456789ABCDEF'
let hex = ''
let num = decimal
while (num > 0) {
hex = hexChars[num % 16] + hex
num = Math.floor(num / 16)
}
return hex
}

export { decimalToHexadecimal }
43 changes: 43 additions & 0 deletions Conversions/test/DecimalToHexadecimal.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { decimalToHexadecimal } from '../DecimalToHexadecimal.js'

describe('decimalToHexadecimal', () => {
test("decimalToHexadecimal(0) returns '0'", () => {
expect(decimalToHexadecimal(0)).toBe('0')
})

test("decimalToHexadecimal(10) returns 'A'", () => {
expect(decimalToHexadecimal(10)).toBe('A')
})

test("decimalToHexadecimal(15) returns 'F'", () => {
expect(decimalToHexadecimal(15)).toBe('F')
})

test("decimalToHexadecimal(16) returns '10'", () => {
expect(decimalToHexadecimal(16)).toBe('10')
})

test("decimalToHexadecimal(255) returns 'FF'", () => {
expect(decimalToHexadecimal(255)).toBe('FF')
})

test("decimalToHexadecimal(256) returns '100'", () => {
expect(decimalToHexadecimal(256)).toBe('100')
})

test("decimalToHexadecimal(4096) returns '1000'", () => {
expect(decimalToHexadecimal(4096)).toBe('1000')
})

test('throws TypeError for negative input', () => {
expect(() => decimalToHexadecimal(-1)).toThrow(TypeError)
})

test('throws TypeError for float input', () => {
expect(() => decimalToHexadecimal(1.5)).toThrow(TypeError)
})

test('throws TypeError for non-number input', () => {
expect(() => decimalToHexadecimal('FF')).toThrow(TypeError)
})
})
Loading