]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - apps/tidep0084.git/blob - example/iot-gateway/node_modules/bytebuffer/src/encodings/hex.js
Initial commit
[apps/tidep0084.git] / example / iot-gateway / node_modules / bytebuffer / src / encodings / hex.js
1 //? if (HEX) {
2 // encodings/hex
4 /**
5  * Encodes this ByteBuffer's contents to a hex encoded string.
6  * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
7  * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
8  * @returns {string} Hex encoded string
9  * @expose
10  */
11 ByteBufferPrototype.toHex = function(begin, end) {
12     begin = typeof begin === 'undefined' ? this.offset : begin;
13     end = typeof end === 'undefined' ? this.limit : end;
14     if (!this.noAssert) {
15         //? ASSERT_RANGE();
16     }
17     //? if (NODE)
18     return this.buffer.toString("hex", begin, end);
19     //? else {
20     var out = new Array(end - begin),
21         b;
22     while (begin < end) {
23         //? if (DATAVIEW)
24         b = this.view.getUint8(begin++);
25         //? else
26         b = this.view[begin++];
27         if (b < 0x10)
28             out.push("0", b.toString(16));
29         else out.push(b.toString(16));
30     }
31     return out.join('');
32     //? }
33 };
35 /**
36  * Decodes a hex encoded string to a ByteBuffer.
37  * @param {string} str String to decode
38  * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
39  *  {@link ByteBuffer.DEFAULT_ENDIAN}.
40  * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
41  *  {@link ByteBuffer.DEFAULT_NOASSERT}.
42  * @returns {!ByteBuffer} ByteBuffer
43  * @expose
44  */
45 ByteBuffer.fromHex = function(str, littleEndian, noAssert) {
46     if (!noAssert) {
47         if (typeof str !== 'string')
48             throw TypeError("Illegal str: Not a string");
49         if (str.length % 2 !== 0)
50             throw TypeError("Illegal str: Length not a multiple of 2");
51     }
52     //? if (NODE) {
53     var bb = new ByteBuffer(0, littleEndian, true);
54     bb.buffer = new Buffer(str, "hex");
55     bb.limit = bb.buffer.length;
56     //? } else {
57     var k = str.length,
58         bb = new ByteBuffer((k / 2) | 0, littleEndian),
59         b;
60     for (var i=0, j=0; i<k; i+=2) {
61         b = parseInt(str.substring(i, i+2), 16);
62         if (!noAssert)
63             if (!isFinite(b) || b < 0 || b > 255)
64                 throw TypeError("Illegal str: Contains non-hex characters");
65         //? if (DATAVIEW)
66         bb.view.setUint8(j++, b);
67         //? else
68         bb.view[j++] = b;
69     }
70     bb.limit = j;
71     //? }
72     return bb;
73 };
75 //? }