UNPKG

thingy-byte-utils

Version:

Some utility functions for transforming bytes to other representations.

66 lines (51 loc) 1.71 kB
// Generated by CoffeeScript 2.7.0 //########################################################### var backHexMap, bigIntMap, decoder, frontHexMap, hexChars, slots; import { StringDecoder } from "string_decoder"; decoder = new StringDecoder("utf-8"); slots = (new Array(256)).fill(0); bigIntMap = slots.map(function(el, idx) { return BigInt(idx); }); //########################################################### hexChars = Array.from("0123456789abcdef"); frontHexMap = new Array(256); // frontHexMap = {} hexChars.forEach(function(el) { return frontHexMap[el] = 16 * parseInt(el, 16); }); backHexMap = new Array(256); // backHexMap = {} hexChars.forEach(function(el) { return backHexMap[el] = parseInt(el, 16); }); //########################################################### export var bytesToBigInt = function(byteBuffer) { var byteArray, hex; byteArray = new Uint8Array(byteBuffer); hex = bytesToHex(byteArray.reverse()); return BigInt("0x" + hex); }; //########################################################### export var bytesToUtf8 = function(byteBuffer) { var byteArray; byteArray = new Uint8Array(byteBuffer); return decoder.end(byteArray); }; export var utf8ToBytes = function(utf8) { return new Uint8Array(Buffer.from(utf8, "utf8")); }; //########################################################### export var bytesToHex = function(byteBuffer) { return Buffer.from(byteBuffer).toString("hex"); }; export var hexToBytes = function(hex) { var i, j, ref, result; result = new Uint8Array(hex.length / 2); for (i = j = 0, ref = hex.length; j < ref; i = j += 2) { result[i / 2] = frontHexMap[hex[i]] + backHexMap[hex[i + 1]]; } return result; };