如何在JavaScript中将十进制转换为十六进制

在本文中,我们将学习如何在 JavaScript 中轻松地将十进制数转换为其等效的十六进制数。

数字 toString() 方法

要在 JavaScript 中将十进制转换为十六进制,请对十进制调用 toString() 方法,将 16 作为基数参数传递,即 num.toString(16)。toString() 方法将以十六进制形式返回数字的字符串表示形式。

例如:

const num = 60;
const hex = num.toString(16);
console.log(hex); // 3c

// Use parentheses when calling toString() directly
const hex2 = (60).toString(16);
console.log(hex2); // 3c

Number toString() 方法返回数字的字符串表示形式。如果第一个参数指定了基数,则数字以该基数表示。我们传递 16 以使用基数 16,这是十六进制基数。

十六进制使用 16 个符号来表示数字:

0 到 9 表示值 0 到 9

a 到 f(A 到 F)表示值 10 到 16。字母不区分大小写,因此 3C2b 与 3c2B 的值完全相同。

在数字文字上调用 toString()

如果直接对数字文字调用 toString(),请确保将其括在括号 (( )) 中或使用两个点 (..before toString():

// Use parentheses
const hex2 = (60).toString(16);
console.log(hex2); // 3c

// Use double dots
const hex3 = 50..toString(16);
console.log(hex3); // 32

如果你只使用一个不带括号的点,JavaScript 解析器会将其视为数字文字的一部分——小数点——而不是成员访问运算符。

console.log(40.); // 40
console.log(20.); // 20

所以会出现错误,因为在成员名称之前没有成员访问运算符。

// SyntaxError
console.log(40.toString(16));

// SyntaxError
console.log(20.toString(16));\

因此,您将数字括在括号中,以便它们之外的所有内容都被视为与数字分开。

console.log((40).toString(16)); // 28

console.log((20).toString(16)); // 14

或者您添加第二个点,它将被视为成员访问运算符。

console.log(40..toString(16)); // 28

console.log(20..toString(16)); // 14

用例:将 RGB(A) 转换为十六进制

将十进制值转换为十六进制值的一种常见用途是将 RGB 颜色代码转换为其等效的十六进制值。我们可以这样做:

function decToHex(dec) {
  return dec.toString(16);
}

function padToTwo(str) {
  return str.padStart(2);
}

function rgbToHex(r, g, b) {
  const hexR = padToTwo(decToHex(r));
  const hexG = padToTwo(decToHex(g));
  const hexB = padToTwo(decToHex(b));

  return `#${hexR}${hexG}${hexB}`;
}

console.log(rgbToHex(255, 128, 237)); // #ff80ed

console.log(rgbToHex(195, 151, 151)); // #c39797

console.log(rgbToHex(16, 16, 16)); // #0f0f0f

我们创建了一个可重用的 rgbToHex() 函数来将 RGB 代码转换为其等效的十六进制代码。

我们使用 padToTwo() 函数将十六进制代码填充为两位数,例如 f -> 0f。

在将 R、G 和 B 的十进制值转换为十六进制表示后,我们将它们连接到一个以 # 字符为前缀的字符串中,以形成十六进制颜色代码。

我们可以修改该函数以使其也接受 RGBA 值,其中 A 是用于指定颜色不透明度的百分比值(介于 0 和 1 之间)。A 将是十六进制颜色代码的前两个字符,其值介于 00(0 或 0%)和 ff(255 或 100%)之间.

function decToHex(dec) {
  return dec.toString(16);
}

function padToTwo(str) {
  return str.padStart(2);
}

function rgbToHex(r, g, b, a) {
  const hexR = padToTwo(decToHex(r));
  const hexG = padToTwo(decToHex(g));
  const hexB = padToTwo(decToHex(b));

  // Set "a" to 1 if not specified
  const aAbsolute = Math.round((a ?? 1) * 255);

  const hexA = padToTwo(decToHex(aAbsolute));

  return `#${hexA}${hexR}${hexG}${hexB}`;
}

console.log(rgbToHex(255, 128, 237)); // #ffff80ed

console.log(rgbToHex(195, 151, 151, 0.5)); // #80c39797

console.log(rgbToHex(16, 16, 16, 0.69)); // #b0101010

猜你喜欢

转载自blog.csdn.net/qq_41838305/article/details/130100484
今日推荐