Skip to content

Commit

Permalink
fix: readBufferFromBigInt not handling signed ints correctly when r…
Browse files Browse the repository at this point in the history
…ead as LE (#46)
  • Loading branch information
rojvv committed May 13, 2023
1 parent 7a81dcb commit 596f7ef
Showing 1 changed file with 10 additions and 28 deletions.
38 changes: 10 additions & 28 deletions src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,38 +127,20 @@ export function readBufferFromBigInt(
}

const hex = bigIntVar.toString(16).padStart(bytesNumber * 2, "0");
let littleBuffer = Buffer.from(hex, "hex");

if (little) {
littleBuffer = littleBuffer.reverse();
}
let buffer = Buffer.from(hex, "hex");

if (signed && below) {
if (little) {
let reminder = false;
if (littleBuffer[0] !== 0) {
littleBuffer[0] -= 1;
}
for (let i = 0; i < littleBuffer.length; i++) {
if (littleBuffer[i] === 0) {
reminder = true;
continue;
}
if (reminder) {
littleBuffer[i] -= 1;
reminder = false;
}
littleBuffer[i] = 255 - littleBuffer[i];
}
} else {
littleBuffer[littleBuffer.length - 1] = 256 -
littleBuffer[littleBuffer.length - 1];
for (let i = 0; i < littleBuffer.length - 1; i++) {
littleBuffer[i] = 255 - littleBuffer[i];
}
buffer[buffer.length - 1] = 256 -
buffer[buffer.length - 1];
for (let i = 0; i < buffer.length - 1; i++) {
buffer[i] = 255 - buffer[i];
}
}
return littleBuffer;

if (little) {
buffer = buffer.reverse();
}
return buffer;
}

export function generateRandomLong(signed = true) {
Expand Down

0 comments on commit 596f7ef

Please sign in to comment.