thingy-byte-utils
Version:
Some utility functions for transforming bytes to other representations.
85 lines (69 loc) • 2.33 kB
JavaScript
// Generated by CoffeeScript 2.7.0
//###########################################################
var backHexMap, bigIntMap, decoder, encoder, frontHexMap, hexChars, hexMap, slots;
encoder = new TextEncoder("utf-8");
decoder = new TextDecoder("utf-8");
//###########################################################
slots = (new Array(256)).fill(0);
hexMap = slots.map(function(el, idx) {
return idx.toString(16).padStart(2, '0');
});
bigIntMap = slots.map(function(el, idx) {
return BigInt(idx);
});
//###########################################################
hexChars = Array.from("0123456789abcdef");
frontHexMap = new Array(256);
hexChars.forEach(function(el) {
return frontHexMap[el] = 16 * parseInt(el, 16);
});
backHexMap = new Array(256);
hexChars.forEach(function(el) {
return backHexMap[el] = parseInt(el, 16);
});
//###########################################################
// export bytesToBigInt = (byteBuffer) ->
// byteBuffer = new Uint8Array(byteBuffer)
// value = 0n
// for byte,i in byteBuffer
// value += bigIntMap[byte] << (8n * bigIntMap[i])
// return value
export var bytesToBigInt = function(byteBuffer) {
var byte, i, j, len, value;
byteBuffer = new Uint8Array(byteBuffer);
value = 0n;
for (i = j = 0, len = byteBuffer.length; j < len; i = ++j) {
byte = byteBuffer[i];
value += BigInt(byte) << (8n * BigInt(i));
}
return value;
};
//###########################################################
export var bytesToUtf8 = function(byteBuffer) {
return decoder.decode(byteBuffer);
};
export var utf8ToBytes = function(utf8) {
// bytes = encoder.encode(utf8)
// return bytes.buffer
return encoder.encode(utf8);
};
//###########################################################
export var bytesToHex = function(byteBuffer) {
var byte, byteArray, j, len, result;
byteArray = new Uint8Array(byteBuffer);
result = "";
for (j = 0, len = byteArray.length; j < len; j++) {
byte = byteArray[j];
result += hexMap[byte];
}
return result;
};
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.buffer
return result;
};