为什么.toString(16)将rgb,十进制或其他输入转换为十六进制 [英] Why does .toString(16) convert rgb, decimal, or other inputs into a hexidecimal

查看:1668
本文介绍了为什么.toString(16)将rgb,十进制或其他输入转换为十六进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在所有可以找到答案的地方进行搜索,以了解.toString(16)为什么将数字转换为十六进制值.我的第一个问题是,为什么16?我的第二个问题是,即使我看不到代码中的字母,这怎么能返回字母.例如,我不明白下面的代码如何返回ff而不是数字.

I've tried searching everywhere I could to find the answer as to why .toString(16) converts a number to a hexidecimal value. My first question is, why 16? My second question is, how can this return letters even though I see no letters going into the code. For example, I don't understand how the following code returns ff instead of a number.

var r = 255;
r.toString(16); //returns ff

如果有人对此有任何链接或见解,请告诉我.我很好奇.预先谢谢你!

If anyone has any links or insights as to why this is, please let me know. I'm very curious. Thank you in advance!

推荐答案

十六进制为基数16.分解单词:hexa,含义为6;十进制,表示10.10+ 6 =16.一些主要的基数是:

Hexadecimal is base 16. Break down the words: hexa, meaning 6; decimal, meaning 10. 10 + 6 = 16. A few major bases are:

  • 基数2:二进制,2个数字:[0,1]
  • 基数8:八进制,8个数字:[0,7]
  • 以10为基数:十进制,10个数字:[0、9]
  • 基数16:十六进制,16个符号:[0,9]和[A,F]

根据 MDN文档 :

对于Number对象,toString()方法以指定的基数返回对象的字符串表示形式.

For Number objects, the toString() method returns a string representation of the object in the specified radix.

参数

基数: 选修的. 2到36之间的整数,指定用于表示数值的基数.

radix: Optional. An integer between 2 and 36 specifying the base to use for representing numeric values.

这意味着它将根据基数将数字转换为字符串. Number.prototype.toString的语法为:

This means it converts the number into a string, and based on the radix. The syntax for Number.prototype.toString is:

number.toString([radix])

radix是可选的.如果指定基数,它将以该基数转换,因此16是十六进制.如果未指定radix,则假定为10(十进制).这是一个片段:

Where radix is optional. If you specify the radix, it will convert with that base, so 16 is hexadecimal. If radix is not specified, 10 (decimal) is assumed. Here's a snippet:

var num = 16;

console.log(num.toString()) //"16", base 10 is assumed here if no radix given
console.log(num.toString(16)) //"10", base 16 is given

现在,关于RGB值:以(255,255,255)[白色]为例.每个单独的值(红色,绿色或蓝色)均以十六进制表示.由于255是0xFF或只是十六进制的FF,因此完整的表示形式是FFFFFFffffff.

Now, regarding RGB values: take (255, 255, 255) [white] as an example. Each individual value (red, green, or blue) is represented in hex. Since 255 is 0xFF or simply FF in hex, the full representation is FFFFFF, or ffffff you see.

这篇关于为什么.toString(16)将rgb,十进制或其他输入转换为十六进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆