msgba-web/js-src/endian.ts

52 lines
1.6 KiB
TypeScript
Raw Normal View History

2023-03-22 13:53:16 +01:00
"use strict";
let littleEndian = true; (()=>{ let buf = new ArrayBuffer(4); let buf8 = new
Uint8ClampedArray(buf); let data = new Uint32Array(buf); data[0] = 0xdeadbeef;
if(buf8[0] === 0xde){ littleEndian = false; } })()
export default class Endian {
static isLittleEndian() {
return littleEndian;
}
static byteArrayToU32BigEndian(inputArray: Uint8Array) {
if (Endian.isLittleEndian()) {
inputArray = inputArray.reverse();
}
const buffer = inputArray.buffer;
const outputU32Array = new Uint32Array(buffer);
return outputU32Array[0];
}
static byteArrayToU64BigEndian(inputArray: Uint8Array) {
if (Endian.isLittleEndian()) {
inputArray = inputArray.reverse();
}
const buffer = inputArray.buffer;
const outputU64Array = new BigUint64Array(buffer);
return outputU64Array[0];
}
static u64ToByteArrayBigEndian(inputNumber: bigint) {
const buffer = new ArrayBuffer(8);
const buffer8 = new Uint8Array(buffer);
const buffer64 = new BigUint64Array(buffer);
buffer64[0] = inputNumber;
if (Endian.isLittleEndian()) {
buffer8.reverse();
}
return buffer8;
}
2023-03-25 15:20:18 +01:00
static u32ToByteArrayBigEndian(inputNumber: number) {
const buffer = new ArrayBuffer(4);
const buffer8 = new Uint8Array(buffer);
const buffer32 = new Uint32Array(buffer);
buffer32[0] = inputNumber;
if (Endian.isLittleEndian()) {
buffer8.reverse();
}
return buffer8;
}
2023-03-22 13:53:16 +01:00
}