Skip to content

Instantly share code, notes, and snippets.

@mauropm
Created April 18, 2012 23:20
Show Gist options
  • Save mauropm/2417308 to your computer and use it in GitHub Desktop.
Save mauropm/2417308 to your computer and use it in GitHub Desktop.
Buffer Operations
/*
* (c) 2012 Mauro Parra-Miranda mauropm@gmail.com
* This functions will get save your buffer to hex, going from hex to buffer
* and will allow you to save a buffer to A JSON and recovering a JSON from the buffer.
*/
bufferToHex = function(buf) {
var res = new Array(buf.length);
for(var idx = 0; idx < buf.length; idx++) {
var b = Ti.Codec.decodeNumber({
source : buf,
position : idx,
type : Ti.Codec.TYPE_BYTE,
byteOrder : Ti.Codec.LITTLE_ENDIAN
});
res[idx] = b.toString(16);
}
return res.toString();
}
hexToBuffer = function(hex) {
var res = hex.split(",");
var buffer = Ti.createBuffer({length : res.length});
for(var i = 0; i < res.length; i++) {
buffer[i]=parseInt(res[i], 16);
}
return buffer;
}
bufferToJSON = function(buf){
return JSON.stringify(bufferToHex(buf));
}
JSONToBuffer = function (jsontext){
return hexToBuffer(JSON.parse(jsontext));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment