Skip to content

Commit

Permalink
fix: dec2hex and dec2bits cannot use >>> for coercion because i…
Browse files Browse the repository at this point in the history
…t only works up to 32 bits

Instead now we do runtime checks to see if the parameters are positive.
At the same time, we have made the `size` parameter optional, if it is
left `undefined`, then the size will be automatically acquired based on
the size of the `dec`.

This means:

```
dec2bits(1) === '1'
dec2bits(100) === '64'
dec2bits(100, 0) === ''
dec2bits(Number.MAX_SAFE_INTEGER, 0) === '1fffffffffffff'
```

Similar for `dec2bits`.
  • Loading branch information
CMCDragonkai committed Oct 3, 2022
1 parent d5db128 commit 556fd6f
Showing 1 changed file with 20 additions and 8 deletions.
28 changes: 20 additions & 8 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,20 +224,32 @@ function bits2bytes(bits: string): Uint8Array {
* Encodes positive base 10 numbers to bit string
* Will output bits in big-endian order
*/
function dec2bits(dec: number, size: number): string {
dec %= 2 ** size;
// `>>>` coerces dec to unsigned integer
return (dec >>> 0).toString(2).padStart(size, '0');
function dec2bits(dec: number, size?: number): string {
if (dec < 0) throw RangeError('`dec` must be positive');
if (size != null) {
if (size < 0) throw RangeError('`size` must be positive');
if (size === 0) return '';
dec %= 2 ** size;
} else {
size = 0;
}
return dec.toString(2).padStart(size, '0');
}

/**
* Encodes positive base 10 numbers to hex string
* Will output hex in big-endian order
*/
function dec2hex(dec: number, size: number): string {
dec %= 16 ** size;
// `>>>` coerces dec to unsigned integer
return (dec >>> 0).toString(16).padStart(size, '0');
function dec2hex(dec: number, size?: number): string {
if (dec < 0) throw RangeError('`dec` must be positive');
if (size != null) {
if (size < 0) throw RangeError('`size` must be positive');
if (size === 0) return '';
dec %= 16 ** size;
} else {
size = 0;
}
return dec.toString(16).padStart(size, '0');
}

/**
Expand Down

0 comments on commit 556fd6f

Please sign in to comment.