Skip to content

Instantly share code, notes, and snippets.

@mauropm
Created April 18, 2012 23:20

Revisions

  1. Mauro Parra-Miranda created this gist Apr 18, 2012.
    37 changes: 37 additions & 0 deletions bufferlib.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    /*
    * (c) 2012 Mauro Parra-Miranda [email protected]
    * 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));
    }