js int 转 uint8array
function intToUint8Array(number) {
// 创建一个8字节的ArrayBuffer
const buffer = new ArrayBuffer(8);
// 创建一个视图来写入这个buffer
const dataView = new DataView(buffer);
// 设置buffer的第一个字节为int32
dataView.setInt32(0, number, true); // true表示使用小端
// 创建Uint8Array视图
return new Uint8Array(buffer);
}
// 示例使用
const intNumber = 123456789;
const uint8Array = intToUint8Array(intNumber);
console.log(uint8Array);
js uint8array 转 int
以下是几种将JS的Uint8Array转换为int的实现方法:
需要翻转unit8array
16909060
方法一:使用TypedArray的reduce方法
const array = new Uint8Array([1, 2, 3, 4]);
let reversedUint8Array = new Uint8Array(uint8Array.slice().reverse());
const result = Array.prototype.reduce.call(reversedUint8Array , (acc, cur) => acc * 256 + cur, 0);
console.log(result); // 输出:67305985
方法二:使用for循环和位运算符
const array = new Uint8Array([1, 2, 3, 4]);
let reversedUint8Array = new Uint8Array(uint8Array.slice().reverse());
let result = 0;
for(let i = 0; i < reversedUint8Array .length; i++) {
result <<= 8;
result |= array[i];
}
console.log(result); // 输出:67305985
方法三:使用BigInt对象进行转换
const array = new Uint8Array([1, 2, 3, 4]);
let reversedUint8Array = new Uint8Array(uint8Array.slice().reverse());
const result = BigInt("0x" + Array.prototype.map.call(reversedUint8Array , x => x.toString(16).padStart(2, "0")).join(""));
console.log(Number(result)); // 输出:16909060
请注意,这些方法都假设输入的Uint8Array每个元素不会大于255,并且Uint8Array的长度在int能够表示的范围内。