如何在 JavaScript 中将十进制转换为十六进制
在 JavaScript 中如何将十进制值转换为相应的十六进制值?
How do you convert decimal values to their hexadecimal equivalent in JavaScript?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
任意精度
该解决方案接受输入十进制字符串,并返回十六进制字符串。 支持小数。 算法
s
)、整数部分 (i
) 和小数部分 (f
),例如-123.75 我们有
s=true
、i=123
、f=75
i='0'
停止m=i%16
(任意精度)m
转换为十六进制数字并放入结果字符串i=i/16
(任意精度)i=i/16
(任意精度)小数部分n
k=f*16
(任意精度)k
拆分为右侧的n
位数字,并将它们放入f
,将左侧的部分与其余数字拆分,并将它们放入<代码>dd
转换为十六进制并添加到结果中。Arbitrary precision
This solution take on input decimal string, and return hex string. A decimal fractions are supported. Algorithm
s
), integer part (i
) and fractional part (f
) e.g for-123.75
we haves=true
,i=123
,f=75
i='0'
stopm=i%16
(in arbitrary precision)m
to hex digit and put to result stringi=i/16
(in arbitrary precision)n
k=f*16
(in arbitrary precision)k
to right part withn
digits and put them tof
, and left part with rest of digits and put them tod
d
to hex and add to result.下面的代码将十进制值 d 转换为十六进制。 它还允许您向十六进制结果添加填充。 所以0默认会变成00。
The code below will convert the decimal value d to hexadecimal. It also allows you to add padding to the hexadecimal result. So 0 will become 00 by default.
AFAIK 评论 57807 是错误的,应该是就像是:
var hex = Number(d).toString(16);
代替
var hex = parseInt(d, 16);
AFAIK comment 57807 is wrong and should be something like:
var hex = Number(d).toString(16);
instead of
var hex = parseInt(d, 16);
正如接受的答案所述,从十进制转换为十六进制的最简单方法是 var hex = dec.toString(16) 。 但是,您可能更愿意添加字符串转换,因为它可以确保
"12".toString(16)
等字符串表示形式正常工作。要反转该过程,您还可以使用下面的解决方案,因为它更短。
它在 Google Chrome 和 Firefox 中似乎较慢,但在 Opera 中明显更快。 请参阅http://jsperf.com/hex-to-dec。
As the accepted answer states, the easiest way to convert from decimal to hexadecimal is
var hex = dec.toString(16)
. However, you may prefer to add a string conversion, as it ensures that string representations like"12".toString(16)
work correctly.To reverse the process you may also use the solution below, as it is even shorter.
It seems to be slower in Google Chrome and Firefox, but is significantly faster in Opera. See http://jsperf.com/hex-to-dec.
我正在一个相当大的循环中进行十六进制字符串的转换,因此我尝试了多种技术来找到最快的技术。 我的要求是得到一个固定长度的字符串作为结果,并正确编码负值(-1 => ff..f)。
简单的
.toString(16)
对我来说不起作用,因为我需要正确编码负值。 以下代码是迄今为止我在 1-2 字节值上测试过的最快的代码(请注意,symbols
定义了您想要获取的输出符号的数量,即对于 4 字节整数,它应该是等于 8):它在 1-2 字节数字上比
.toString(16)
执行得更快,在更大的数字上执行得更慢(当symbols
>= 6 时),但仍然应该优于正确编码负值的方法。I'm doing conversion to hex string in a pretty large loop, so I tried several techniques in order to find the fastest one. My requirements were to have a fixed-length string as a result, and encode negative values properly (-1 => ff..f).
Simple
.toString(16)
didn't work for me since I needed negative values to be properly encoded. The following code is the quickest I've tested so far on 1-2 byte values (note thatsymbols
defines the number of output symbols you want to get, that is for 4-byte integer it should be equal to 8):It performs faster than
.toString(16)
on 1-2 byte numbers and slower on larger numbers (whensymbols
>= 6), but still should outperform methods that encode negative values properly.您可以在 ECMAScript 6 中执行类似的操作:
You can do something like this in ECMAScript 6:
如果您正在寻找转换大整数,即大于 Number.MAX_SAFE_INTEGER -- 9007199254740991 的数字,那么您可以使用以下代码
If you are looking for converting Large integers i.e. Numbers greater than Number.MAX_SAFE_INTEGER -- 9007199254740991, then you can use the following code
如何在 JavaScript 中将十进制转换为十六进制
我无法找到一个非常干净/简单的十进制到十六进制的转换,并且不涉及一堆函数和数组......所以我不得不做这是给我自己的。
How to convert decimal to hexadecimal in JavaScript
I wasn't able to find a brutally clean/simple decimal to hexadecimal conversion that didn't involve a mess of functions and arrays ... so I had to make this for myself.
这是基于 Prestaul 和 Tod's 的解决方案。 然而,这是一个概括,说明了变量大小的变化(例如,从微控制器串行日志中解析有符号值)。
测试脚本:
测试结果:
注意:不太清楚为什么它在 32 位以上失败
This is based on Prestaul and Tod's solutions. However, this is a generalisation that accounts for varying size of a variable (e.g. Parsing signed value from a microcontroller serial log).
Test script:
Test results:
Note: Not too sure why it fails above 32 bitsize
我还没有找到一个明确的答案,没有检查它是负数还是正数,它使用二进制补码(包括负数)。 为此,我展示了针对一个字节的解决方案:
您可以将此指令用于任意数量的字节,只需在相应的位置添加
FF
即可。 例如,到两个字节:如果要将数组整数转换为十六进制字符串:
I haven't found a clear answer, without checks if it is negative or positive, that uses two's complement (negative numbers included). For that, I show my solution to one byte:
You can use this instruction to any number bytes, only you add
FF
in respective places. For example, to two bytes:If you want cast an array integer to string hexadecimal:
总结一下;
但是,如果您不需要在末尾将其转换回整数(即颜色),那么只需确保这些值不是负数就足够了。
To sum it all up;
However, if you don't need to convert it back to an integer at the end (i.e. for colors), then just making sure the values aren't negative should suffice.
rgb(255, 255, 255) // 返回 FFFFFF
rgb(255, 255, 300) // 返回 FFFFFF
rgb(0,0,0) // 返回 000000
rgb(148, 0, 211) // 返回 9400D3
rgb(255, 255, 255) // returns FFFFFF
rgb(255, 255, 300) // returns FFFFFF
rgb(0,0,0) // returns 000000
rgb(148, 0, 211) // returns 9400D3
如果您希望转换为“完整”JavaScript 或 CSS 表示形式,您可以使用以下内容:
In case you're looking to convert to a 'full' JavaScript or CSS representation, you can use something like:
问题基本上是期望有多少个填充零。
如果您希望数字 1 和 17 中包含字符串
01
和11
。最好使用 Buffer 作为桥梁,将数字转换为字节,然后十六进制只是它的输出格式。 并且字节组织由 Buffer 函数很好地控制,例如 writeUInt32BE,writeInt16LE, ETC。The problem basically how many padding zeros to expect.
If you expect string
01
and11
from Number 1 and 17. it's better to use Buffer as a bridge, with which number is turn into bytes, and then the hex is just an output format of it. And the bytes organization is well controlled by Buffer functions, like writeUInt32BE, writeInt16LE, etc.这是我的解决方案:
问题是:“如何在 JavaScript 中将十进制转换为十六进制”。 虽然问题没有指定十六进制字符串应以 0x 前缀开头,但任何编写代码的人都应该知道,在十六进制代码中添加 0x 是为了区分十六进制代码和编程标识符 em> 和其他数字(1234 可以是十六进制、十进制,甚至八进制)。
因此,要正确回答这个问题,为了编写脚本,必须添加0x前缀。
Math.abs(N) 函数将负数转换为正数,而且作为奖励,它看起来不像有人通过木材削片机运行它。
我想要的答案应该有一个字段宽度说明符,因此我们可以以十六进制编辑应用程序中列出的方式显示 8/16/32/64 位值。 这就是实际的、正确的答案。
Here's my solution:
The question says: "How to convert decimal to hexadecimal in JavaScript". While, the question does not specify that the hexadecimal string should begin with a 0x prefix, anybody who writes code should know that 0x is added to hexadecimal codes to distinguish hexadecimal codes from programmatic identifiers and other numbers (1234 could be hexadecimal, decimal, or even octal).
Therefore, to correctly answer this question, for the purpose of script-writing, you must add the 0x prefix.
The Math.abs(N) function converts negatives to positives, and as a bonus, it doesn't look like somebody ran it through a wood-chipper.
The answer I wanted, would have had a field-width specifier, so we could for example show 8/16/32/64-bit values the way you would see them listed in a hexadecimal editing application. That, is the actual, correct answer.
为了完整起见,如果您想要二的补码负数的十六进制表示,您可以使用 零填充右移
>>>
运算符。 例如:但是有一个限制: JavaScript 按位运算符将其操作数视为 32 位序列,也就是说,您将获得 32 位二进制补码。
For completeness, if you want the two's-complement hexadecimal representation of a negative number, you can use the zero-fill-right shift
>>>
operator. For instance:There is however one limitation: JavaScript bitwise operators treat their operands as a sequence of 32 bits, that is, you get the 32-bits two's complement.
接受的答案没有考虑单个数字返回的十六进制代码。 这很容易通过以下方式进行调整:
并且
我相信上述答案已被其他人以一种或另一种形式发布过多次。 我将它们包装在 toHex() 函数中,如下所示:
请注意,数字正则表达式来自 10 多个有用的 JavaScript 正则表达式函数可提高您的 Web 应用程序效率。
更新:经过多次测试后,我发现了一个错误(正则表达式中的双引号),所以我修复了这个错误。 然而! 经过相当多的测试并阅读了 almaz 的帖子 - 我意识到我无法让负数起作用。
此外 - 我对此进行了一些阅读,因为无论如何,所有 JavaScript 数字都存储为 64 位字 - 我尝试修改 numHex 代码以获取 64 位字。 但事实证明你不能那样做。 如果您将“3.14159265”作为数字放入变量中 - 您将能够得到的只是“3”,因为小数部分只能通过将数字重复乘以十(即:10.0)来访问。 或者换句话说 - 0xF 的十六进制值会导致浮点值在进行 AND 运算之前被转换为整数,从而删除一切都落后于时代。 而不是将值作为一个整体(即:3.14159265)并将浮点值与 0xF 值进行“与”运算。
因此,在这种情况下,最好的办法是将 3.14159265 转换为 字符串,然后只转换该字符串。 由于上述原因,它也使得负数转换变得很容易,因为减号正好变成值前面的 0x26。
所以我所做的就是确定变量包含一个数字 - 只需将其转换为字符串并转换该字符串。 这对每个人来说意味着在服务器端您需要对传入的字符串进行十六进制处理,然后确定传入的信息是数字。 只需在数字前面添加“#”,在返回的字符串前面添加“A”,即可轻松完成此操作。 请参阅 toHex() 函数。
玩得开心!
经过一年的大量思考,我决定“toHex”函数(我也有一个“fromHex”函数)确实需要修改。 整个问题是“我怎样才能更有效地做到这一点?” 我决定 to/from 十六进制函数不应该关心某些内容是否是小数部分,但同时它应该确保小数部分包含在字符串中。
那么问题就变成了“你怎么知道你正在使用十六进制字符串?”。 答案很简单。 使用世界范围内已经认可的标准预串信息。
换句话说 - 使用“0x”。 所以现在我的 toHex 函数会查看它是否已经存在,如果存在 - 它只返回发送给它的字符串。 否则,它会转换字符串、数字等。 这是修改后的 toHex 函数:
这是一个非常快的函数,它考虑了个位数、浮点数,甚至检查该人是否正在发送十六进制值以再次进行十六进制处理。 它仅使用四个函数调用,并且其中只有两个在循环中。 要取消使用的值的十六进制:
与 toHex() 函数一样,fromHex() 函数首先查找“0x”,然后将传入的信息转换为字符串(如果它还不是字符串)。 我不知道它怎么不会是一个字符串 - 但以防万一 - 我检查一下。 然后该函数会执行,抓取两个字符并将它们转换为 ASCII 字符。 如果您希望它转换 Unicode,则需要将循环更改为一次转换四 (4) 个字符。 但是您还需要确保该字符串不能被四整除。 如果是 - 那么它是一个标准的十六进制字符串。 (请记住该字符串前面有“0x”。)
一个简单的测试脚本,用于显示 -3.14159265 在转换为字符串时仍然是 -3.14159265。
由于 JavaScript 与 toString() 函数相关的工作方式,所有这些以前导致问题的问题都可以被消除。 现在所有字符串和数字都可以轻松转换。 此外,诸如对象之类的东西会导致 JavaScript 本身产生错误。 我相信这已经是最好的了。 剩下的唯一改进是 W3C 在 JavaScript 中仅包含 toHex() 和 fromHex() 函数。
更新:阅读下面的评论后,第一个 IF 语句应该在测试之后,以查看“s”是否是字符串。
The accepted answer did not take into account single digit returned hexadecimal codes. This is easily adjusted by:
and
I believe the above answers have been posted numerous times by others in one form or another. I wrap these in a toHex() function like so:
Note that the numeric regular expression came from 10+ Useful JavaScript Regular Expression Functions to improve your web applications efficiency.
Update: After testing this thing several times I found an error (double quotes in the RegExp), so I fixed that. HOWEVER! After quite a bit of testing and having read the post by almaz - I realized I could not get negative numbers to work.
Further - I did some reading up on this and since all JavaScript numbers are stored as 64 bit words no matter what - I tried modifying the numHex code to get the 64 bit word. But it turns out you can not do that. If you put "3.14159265" AS A NUMBER into a variable - all you will be able to get is the "3", because the fractional portion is only accessible by multiplying the number by ten(IE:10.0) repeatedly. Or to put that another way - the hexadecimal value of 0xF causes the floating point value to be translated into an integer before it is ANDed which removes everything behind the period. Rather than taking the value as a whole (i.e.: 3.14159265) and ANDing the floating point value against the 0xF value.
So the best thing to do, in this case, is to convert the 3.14159265 into a string and then just convert the string. Because of the above, it also makes it easy to convert negative numbers because the minus sign just becomes 0x26 on the front of the value.
So what I did was on determining that the variable contains a number - just convert it to a string and convert the string. This means to everyone that on the server side you will need to unhex the incoming string and then to determine the incoming information is numeric. You can do that easily by just adding a "#" to the front of numbers and "A" to the front of a character string coming back. See the toHex() function.
Have fun!
After another year and a lot of thinking, I decided that the "toHex" function (and I also have a "fromHex" function) really needed to be revamped. The whole question was "How can I do this more efficiently?" I decided that a to/from hexadecimal function should not care if something is a fractional part but at the same time it should ensure that fractional parts are included in the string.
So then the question became, "How do you know you are working with a hexadecimal string?". The answer is simple. Use the standard pre-string information that is already recognized around the world.
In other words - use "0x". So now my toHex function looks to see if that is already there and if it is - it just returns the string that was sent to it. Otherwise, it converts the string, number, whatever. Here is the revised toHex function:
This is a very fast function that takes into account single digits, floating point numbers, and even checks to see if the person is sending a hex value over to be hexed again. It only uses four function calls and only two of those are in the loop. To un-hex the values you use:
Like the toHex() function, the fromHex() function first looks for the "0x" and then it translates the incoming information into a string if it isn't already a string. I don't know how it wouldn't be a string - but just in case - I check. The function then goes through, grabbing two characters and translating those in to ASCII characters. If you want it to translate Unicode, you will need to change the loop to going by four(4) characters at a time. But then you also need to ensure that the string is NOT divisible by four. If it is - then it is a standard hexadecimal string. (Remember the string has "0x" on the front of it.)
A simple test script to show that -3.14159265, when converted to a string, is still -3.14159265.
Because of how JavaScript works in respect to the toString() function, all of those problems can be eliminated which before were causing problems. Now all strings and numbers can be converted easily. Further, such things as objects will cause an error to be generated by JavaScript itself. I believe this is about as good as it gets. The only improvement left is for W3C to just include a toHex() and fromHex() function in JavaScript.
Update : After reading the comments below, the first IF statement should come after the test to see if "s" is a string.
带填充:
With padding:
如果您想将数字转换为 RGBA 颜色值的十六进制表示形式,我发现这是这里的几个技巧的最有用组合:
If you want to convert a number to a hexadecimal representation of an RGBA color value, I've found this to be the most useful combination of several tips from here:
没有循环:
另外,不使用必须评估的循环测试不是更好吗?
例如,而不是:
有
Without the loop:
Also isn't it better not to use loop tests that have to be evaluated?
For example, instead of:
have
结合 RGB 值到十六进制函数的一些好主意(在 HTML/CSS 的其他位置添加
#
):Combining some of these good ideas for an RGB-value-to-hexadecimal function (add the
#
elsewhere for HTML/CSS):对于任何感兴趣的人,这里有一个 JSFiddle 比较了这个问题的大多数答案。
这是我最终采用的方法:
另外,请记住,如果您希望将十进制转换为十六进制以在 CSS 中用作 颜色数据类型,您可能更喜欢从小数中提取 RGB 值并使用 rgb()。
例如(JSFiddle):
这设置了
#some-element
的CSS <将 code>color 属性更改为rgb(64, 62, 154)
。For anyone interested, here's a JSFiddle comparing most of the answers given to this question.
And here's the method I ended up going with:
Also, bear in mind that if you're looking to convert from decimal to hex for use in CSS as a color data type, you might instead prefer to extract the RGB values from the decimal and use rgb().
For example (JSFiddle):
This sets
#some-element
's CSScolor
property torgb(64, 62, 154)
.限制/填充到一定数量的字符:
Constrained/padded to a set number of characters:
16 是基数,十六进制数有 16 个值:-)
The 16 is the radix and there are 16 values in a hexadecimal number :-)
将十六进制颜色数字转换为十六进制颜色字符串:
使用
toString
和 ES6padStart
的简单解决方案,用于将十六进制颜色数字转换为十六进制颜色字符串。例如:
0x000000
将变为#000000
0xFFFFFF
将变为#FFFFFF
在此处的小提琴中查看此示例
Converting hex color numbers to hex color strings:
A simple solution with
toString
and ES6padStart
for converting hex color numbers to hex color strings.For example:
0x000000
will become#000000
0xFFFFFF
will become#FFFFFF
Check this example in a fiddle here
如果数字是负数呢?
这是我的版本。
And if the number is negative?
Here is my version.
如果您需要处理位字段或 32 位颜色等内容,那么您需要处理带符号的数字。 JavaScript 函数
toString(16)
将返回一个负的十六进制数,这通常不是您想要的。 这个函数做了一些疯狂的加法,使其成为一个正数。If you need to handle things like bit fields or 32-bit colors, then you need to deal with signed numbers. The JavaScript function
toString(16)
will return a negative hexadecimal number which is usually not what you want. This function does some crazy addition to make it a positive number.使用以下命令将数字转换为十六进制字符串:
并使用以下命令反转该过程:
Convert a number to a hexadecimal string with:
And reverse the process with: