如何在javascript中将整数数组转换为十六进制字符串,反之亦然
我在 javascript 中有 32 位整数数组。 如何将其转换为十六进制字符串 并在需要时再次从该十六进制字符串构建相同的 32 位整数数组?
hexString = yourNumber.toString(16); 可用于将数字转换为十六进制 但是当数字数组转换为十六进制字符串(它将是连续的或由某个字符分隔)时,如何从该字符串中获取数字数组?
I have array of 32 bit integers in javascript.
How to convert it into the Hex string
and again build the same 32 bit integer array from that Hex string when required?
hexString = yourNumber.toString(16);
can be used to convert number to hex
but when array of numbers is converted into Hex string (it will be continuous or separated by some character) then how do I get back array of numbers from that string?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
如果你想不加逗号
[3546,-24,99999,3322]
==>"00000ddaffffffe80001869f00000cfa"
然后您可以为每个数字使用 8 个十六进制数字构建字符串。当然,您必须对短于 8 个十六进制数字的数字进行零填充。并且您必须确保数字使用 twos-compliment 进行编码才能正确处理任何负值。
具体操作方法如下:
这里有一个 jsFiddle,它显示了上述示例。
If you want to do it without commas
[3546,-24,99999,3322]
==>"00000ddaffffffe80001869f00000cfa"
then you can build up the string using 8 hex-digits for each number. Of course, you'll have to zero-pad numbers that are shorter than 8 hex-digits. And you'll have to ensure that the numbers are encoded with twos-compliment to properly handle any negative values.
Here's how to do that:
here's a jsFiddle that shows the above example.
给你:
http://jsfiddle.net/whT2m/
ADDENDUM
OP询问是否使用逗号以外的分隔符。只需要稍作调整即可。这是使用分号的版本:
http://jsfiddle.net/DEbUs/
Here you go:
http://jsfiddle.net/whT2m/
ADDENDUM
The OP asked about using a separator other than a comma. Only a small tweak is needed. Here is a version using the semicolon:
http://jsfiddle.net/DEbUs/
http://jsfiddle.net/YVdqY/
http://jsfiddle.net/YVdqY/
这里有两个使用纯 JavaScript 进行转换的函数,它们应该适用于所有浏览器:
并且,一个工作演示:http: //jsfiddle.net/jfriend00/3vmNs/
Here are two functions to do the conversions using plain javascript that should work in all browsers:
And, a working demo: http://jsfiddle.net/jfriend00/3vmNs/
十六进制字符串到整数数组(例如,0E0006006200980000000000000000)
Hex string to integer array(ex, 0E0006006200980000000000000000)
使用此:
来源:http://javascript.about.com/library/blh2d.htm
Use this:
Source: http://javascript.about.com/library/blh2d.htm
您可以调用 parseInt(hexString, 16) 将十六进制字符串转换为整数值。
You can call parseInt(hexString, 16) to convert a hex string to an integer value.
如果你想使用像“400”这样的大数字(> 255),你必须为每个数组成员添加填充
If you want to use large numbers (>255) like "400" you have to add padding to every array member