I've been doing some work on logical arithmetic recently. I want to encode unsigned integers (Uint's) and signed integers (Int's) as bytes.
Below is a code snippet that currently translates UInts to bytes and vice versa. Unfortunately I got some problems while encoding signed integers with my tactic.
Encoding for Integers will be performed using this shift and mask method for both - unsigned and signed integers.
for (let i=0; i<n; i++)
buffer.push((value >>> (i*8)) & 0xFF);
So what is wrong with my readInt-method and how to fix this?
const buffer = [];
const writeIntN = (value, n) => {
for (let i=0; i<n; i++)
buffer.push((value >>> (i*8)) & 0xFF);
}
const readUint = (n, offset) => {
let v=0;
for (let i=0; i<n; i++)
v |= (buffer[offset++] << (i*8));
return v >>> 0;
}
const readInt = (n, offset) => {
return readUint(n, offset) << (8*n) >> (8*n); // error is here
}
const writeUInt16 = (value) => writeIntN(value, 2);
const readUInt16 = (offset) => readUint(2, offset);
const writeInt16 = (value) => writeIntN(value, 2);
const readInt16 = (offset) => readInt(2, offset);
const writeInt8 = (value) => writeIntN(value, 1);
const readInt8 = (offset) => readInt(1, offset);
writeUInt16(20);
writeInt16(-20);
writeInt8(-42);
console.log(buffer);
console.log(readUInt16(0));
console.log(readInt16(2));
console.log(readInt8(4)); // how?
Note: I know about the basic operations to decode 8,16-bit signed ints but how to get this inside the for loop in readUint more efficient?
Decoding 8-bit signed integers: (buffer[offset++] << 24) >> 24
Decoding 16-bit signed integers: (((buffer[offset++] << 0) | (buffer[offset++] << 8)) << 16) >> 16