Created
May 10, 2015 11:22
-
-
Save tomfa/706d10fed78c497731ac to your computer and use it in GitHub Desktop.
JSON to 8-bit-integer parsing (and visa versa)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// JSON to Uint8Array parsing and visa versa | |
// (Intended Bluetooth communication on Cordova) | |
var JsonToArray = function(json) | |
{ | |
var str = JSON.stringify(json, null, 0); | |
var ret = new Uint8Array(str.length); | |
for (var i = 0; i < str.length; i++) { | |
ret[i] = str.charCodeAt(i); | |
} | |
return ret | |
}; | |
var binArrayToJson = function(binArray) | |
{ | |
var str = ""; | |
for (var i = 0; i < binArray.length; i++) { | |
str += String.fromCharCode(parseInt(binArray[i])); | |
} | |
return JSON.parse(str) | |
} |
Here's a better way to do that
http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript
This worked for me: JSON.parse(binArrayToJson(binArray))
Same but oneliner: (event) => Array.from(new Uint8Array(binarray.buffer)).map(v => String.fromCharCode(v)).join('')
Using TextDecoder: new TextDecoder().decode(new Uint8Array(binarray.buffer))
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks man, it helps a lot