Skip to content

Instantly share code, notes, and snippets.

@tomfa
Created May 10, 2015 11:22
Show Gist options
  • Save tomfa/706d10fed78c497731ac to your computer and use it in GitHub Desktop.
Save tomfa/706d10fed78c497731ac to your computer and use it in GitHub Desktop.
JSON to 8-bit-integer parsing (and visa versa)
// 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)
}
@DreamAndDead
Copy link

thanks man, it helps a lot

@DreamAndDead
Copy link

@jghorton14
Copy link

This worked for me: JSON.parse(binArrayToJson(binArray))

@damiencorpataux
Copy link

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