我将数据作为 BINARY(16)
存储在 SQLite
数据库中,其值由 PHP
的 hex2bin
函数确定在 32 个字符的十六进制字符串上。
例如,字符串 434e405b823445c09cb6c359fb1b7918
返回 CN@[4EÀ¶ÃYûy
。
存储在该数据库中的数据需要通过 JavaScript
进行操作,为此我使用了以下函数(改编自 Andris 的回答 here ):
// Convert hexadecimal to binary string
String.prototype.hex2bin = function ()
{
// Define the variables
var i = 0, l = this.length - 1, bytes = []
// Iterate over the nibbles and convert to binary string
for (i; i < l; i += 2)
{
bytes.push(parseInt(this.substr(i, 2), 16))
}
// Return the binary string
return String.fromCharCode.apply(String, bytes)
}
这按预期工作,从 434e405b823445c09cb6c359fb1b7918
返回 CN@[4EÀ¶ÃYûy
。
但是,我遇到的问题是,当直接处理 PHP
的 hex2bin
函数返回的数据时,我得到了字符串 CN@[ �4E����Y�y
而不是 CN@[4EÀ¶ÃYûy
。这让我无法在两者之间工作(对于上下文,JavaScript
用于驱动离线 iPad 应用程序,该应用程序处理从 PHP
网络应用程序检索的数据) 因为我需要能够使用 JavaScript
生成 32 个字符的十六进制字符串,将其转换为二进制字符串,并让它与 PHP
的 一起工作>hex2bin
函数(和 SQLite
的 HEX
函数)。
我认为,这个问题是 JavaScript
使用 UTF-16
而二进制字符串存储为 utf8_unicode_ci
。然后,我最初的想法是我需要将字符串转换为 UTF-8
。使用 Google 搜索找到了 here,搜索 StackOverflow 找到了 bobince 的答案 here,两者都推荐使用 unescape(encodeURIComponent(str))
。但是,这确实返回了我需要的内容 (CN@[�4E����Y�y
):
// CN@[Â4EöÃYûy
unescape(encodeURIComponent('434e405b823445c09cb6c359fb1b7918'.hex2bin()))
那么我的问题是:
如何使用 JavaScript
将十六进制字符串转换为 UTF-8
二进制字符串?
最佳答案
给定一个十六进制编码的 UTF-8 字符串,`hex',
hex.replace(/../g, '%$&')
将生成 URI 编码的 UTF-8 字符串。
decodeURIComponent
将 URI 编码的 UTF-8 序列转换成 JavaScript UTF-16 编码的字符串,所以
decodeURIComponent(hex.replace(/../g, '%$&'))
应该解码正确的十六进制编码的 UTF-8 字符串。
您可以通过将它应用于 hex2bin
文档中的示例来看到它的工作原理。
alert(decodeURIComponent('6578616d706c65206865782064617461'.replace(/../g, '%$&')));
// alerts "example hex data"
您提供的字符串不是 UTF-8 编码的。具体来说,
434e405b823445c09cb6c359fb1b7918
^
82 必须跟在一个至少设置了前两位的字节之后,而 5b 不是这样的字节。
RFC 2279解释:
The table below summarizes the format of these different octet types. The letter x indicates bits available for encoding bits of the UCS-4 character value.
UCS-4 range (hex.) UTF-8 octet sequence (binary) 0000 0000-0000 007F 0xxxxxxx 0000 0080-0000 07FF 110xxxxx 10xxxxxx 0000 0800-0000 FFFF 1110xxxx 10xxxxxx 10xxxxxx
关于php - 使用UTF8的Javascript十六进制到二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15481059/