Skip to content

Commit ef4be8e

Browse files
Kropiunigjxom
andauthored
fix: handle odd-length hex in signed hexToBigInt / hexToNumber (#4913)
* fix: handle odd-length hex in signed hexToBigInt / hexToNumber * chore: shorten signed hex changeset --------- Co-authored-by: jxom <7336481+jxom@users.noreply.github.com>
1 parent 5df9819 commit ef4be8e

3 files changed

Lines changed: 15 additions & 1 deletion

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"viem": patch
3+
---
4+
5+
Fixed signed `hexToBigInt` and `hexToNumber` calls with odd-length hex values.

src/utils/encoding/fromHex.test.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,10 @@ describe('converts hex to number', () => {
4646
expect(hexToNumber('0x00027760a62ec2ac', { signed: true })).toBe(
4747
694206942069420,
4848
)
49+
50+
// odd-length hex
51+
expect(hexToNumber('0x0', { signed: true })).toBe(0)
52+
expect(hexToNumber('0x1a4', { signed: true })).toBe(420)
4953
})
5054

5155
test('args: size', () => {
@@ -129,6 +133,11 @@ describe('converts hex to bigint', () => {
129133
{ signed: true },
130134
),
131135
).toBe(-12312312312312312412n)
136+
137+
// odd-length hex
138+
expect(hexToBigInt('0x0', { signed: true })).toBe(0n)
139+
expect(hexToBigInt('0xf', { signed: true })).toBe(15n)
140+
expect(hexToBigInt('0x1a4', { signed: true })).toBe(420n)
132141
})
133142

134143
test('args: size', () => {

src/utils/encoding/fromHex.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ export function hexToBigInt(hex: Hex, opts: HexToBigIntOpts = {}): bigint {
137137
const value = BigInt(hex)
138138
if (!signed) return value
139139

140-
const size = (hex.length - 2) / 2
140+
const size = Math.ceil((hex.length - 2) / 2)
141141
const max = (1n << (BigInt(size) * 8n - 1n)) - 1n
142142
if (value <= max) return value
143143

0 commit comments

Comments
 (0)