I have data stored in an SQLite database as BINARY(16) , the value of which is determined by PHP hex2bin in a 32-character hexadecimal string.
As an example, line 434e405b823445c09cb6c359fb1b7918 returns CN@ [4EÀ¶ÃYûy .
The data stored in this database must be processed by JavaScript , and for this I used the following function (adapted from Andris answer 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) }
This works as expected, returning CN@ [4EÀ¶ÃYûy from 434e405b823445c09cb6c359fb1b7918 .
However, the problem is that when I directly access the data returned by the PHP hex2bin function, I hex2bin string CN@ [ 4E Y y , and not CN@ [4EÀ¶ÃYûy . This makes it impossible for me to work between them (for context, JavaScript used to include a stand-alone iPad application that works with data received from a PHP web application), since I need to be able to use JavaScript to generate a 32-character hexadecimal string, convert put it into a binary string and work with the PHP function hex2bin (and SQLite HEX ).
This problem, I believe, is that JavaScript uses UTF-16 , while the binary string is saved as utf8_unicode_ci . My initial thought was that I needed to convert the string to UTF-8 . Using a Google search led me to here and a search on StackOverflow led me to a bobince answer here , both of which recommend using unescape(encodeURIComponent(str)) . However, this returns what I need ( CN@ [ 4E Y y ):
// CN@ [Â4EöÃYûy unescape(encodeURIComponent('434e405b823445c09cb6c359fb1b7918'.hex2bin()))
So my question is:
How to use JavaScript to convert a hexadecimal string to a binary string UTF-8 ?