To convert a decimal integer to a hexadecimal string in JavaScript, call num.toString(16) for standard safe integers (or bigIntVal.toString(16) for BigInt values), and use .toUpperCase() or .padStart(...) when you need uppercase letters or fixed-width hex digits. Always validate that the input is a safe integer (or valid BigInt) first, because non-integers, NaN, Infinity, or numbers beyond Number.MAX_SAFE_INTEGER can produce fractional hex outputs or lose integer precision.
1. Basic Conversion with Number.prototype.toString(16)
Calling .toString(16) on a JavaScript integer converts it to a lowercase base-16 string; for negative integers, JavaScript automatically prefixes a minus sign (-) rather than two’s-complement bits:
// Convert a safe decimal integer to a hexadecimal string
function decimalToHex(value, { uppercase = false, padLength = 0, prefix = "" } = {}) {
if (typeof value !== "number" || !Number.isSafeInteger(value)) {
throw new RangeError("Expected a safe integer within Number.MIN_SAFE_INTEGER to MAX_SAFE_INTEGER.");
}
const isNegative = value < 0;
const absHexRaw = Math.abs(value).toString(16);
const casedHex = uppercase ? absHexRaw.toUpperCase() : absHexRaw.toLowerCase();
const paddedHex = padLength > 0 ? casedHex.padStart(padLength, "0") : casedHex;
const signPrefix = isNegative ? "-" : "";
return `${signPrefix}${prefix}${paddedHex}`;
}
// Example usage:
console.log(decimalToHex(255)); // "ff"
console.log(decimalToHex(255, { uppercase: true, prefix: "0x" })); // "0xFF"
console.log(decimalToHex(10, { padLength: 2, uppercase: true })); // "0A"
console.log(decimalToHex(-26, { prefix: "0x" })); // "-0x1a"
Number.isSafeInteger()safeguard: Rejects floats like12.5(which.toString(16)turns into"c.8"),NaN,Infinity, and integers above9007199254740991(2^53 - 1) where precision is already lost.- Negative numbers:
.toString(16)uses a leading-sign rather than fixed-width two’s-complement representation.
2. Converting Large Integers Beyond MAX_SAFE_INTEGER with BigInt
When working with 64-bit IDs, hashes, or integers larger than Number.MAX_SAFE_INTEGER (9007199254740991), convert or pass a BigInt and call .toString(16) on the BigInt so no digits are rounded away:
// Convert a BigInt (or integer string/number) to a hexadecimal string safely
function bigIntToHex(input, { uppercase = false, prefix = "" } = {}) {
let bigValue;
if (typeof input === "bigint") {
bigValue = input;
} else if (typeof input === "string" && /^[+-]?\d+$/.test(input.trim())) {
bigValue = BigInt(input.trim());
} else if (typeof input === "number" && Number.isSafeInteger(input)) {
bigValue = BigInt(input);
} else {
throw new TypeError("Expected a BigInt, integer string, or safe integer.");
}
const isNegative = bigValue < 0n;
const absValue = isNegative ? -bigValue : bigValue;
const hex = absValue.toString(16);
const formatted = uppercase ? hex.toUpperCase() : hex.toLowerCase();
const signPrefix = isNegative ? "-" : "";
return `${signPrefix}${prefix}${formatted}`;
}
// Example usage:
console.log(bigIntToHex(9007199254740993n, { prefix: "0x" })); // "0x20000000000001"
console.log(bigIntToHex("18446744073709551615", { uppercase: true })); // "FFFFFFFFFFFFFFFF"
- No mixing
NumberandBigInt: KeepBigIntvalues (16n,0n) consistent in arithmetic or comparisons to avoidTypeErrorexceptions. - String input for large decimals: Passing large decimal numbers as strings (
"18446744073709551615") intoBigInt(...)avoids losing precision before conversion even starts.
3. Formatting RGB Channels or Byte Arrays as Hex
A common UI task is converting individual 0–255 RGB channel integers into a hex color string or formatting byte values with two-digit padding:
// Convert red, green, and blue integers (0..255) into a #RRGGBB hex string
function rgbToHex(r, g, b) {
const channels = [r, g, b];
for (const channel of channels) {
if (typeof channel !== "number" || !Number.isInteger(channel) || channel < 0 || channel > 255) {
throw new RangeError("Each RGB channel must be an integer between 0 and 255.");
}
}
const hexParts = channels.map((ch) => ch.toString(16).padStart(2, "0").toUpperCase());
return `#${hexParts.join("")}`;
}
// Example usage:
console.log(rgbToHex(0, 128, 255)); // "#0080FF"
- Pad single-digit channels:
.padStart(2, "0")ensures values like15("f") become"0F"rather than breakinglength. - Strict range bounds: Clamping or rejecting values outside
0..255prevents invalid color strings.
TL;DR: Convert a decimal integer to hexadecimal in JavaScript using num.toString(16) (after checking Number.isSafeInteger(num)), use BigInt(...).toString(16) for integers larger than 2^53 - 1, and apply .toUpperCase() / .padStart() when formatting uppercase or fixed-width hex strings.
