Skip to content

Commit

Permalink
uint256 to words
Browse files Browse the repository at this point in the history
  • Loading branch information
notJoon committed Feb 29, 2024
1 parent 9399382 commit 16b382f
Show file tree
Hide file tree
Showing 3 changed files with 106 additions and 0 deletions.
18 changes: 18 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package main

import (
"fmt"

"github.com/gnoswap-labs/int256/word"
"github.com/holiman/uint256"
)

func main() {
num, _ := uint256.FromHex("0x1234567890abcdef1234567890abcdef1234567890abcdef1234544440abcdef")

w := word.ToWords(num)

for i := 0; i < 8; i++ {
fmt.Printf("%d: %x\n", i, w.Words[i])
}
}
26 changes: 26 additions & 0 deletions word/word.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package word

import (
"encoding/binary"

"github.com/holiman/uint256"
)

type Uint32Words struct {
Words [8]uint32
}

func ToWords(num *uint256.Int) *Uint32Words {
// convert uint256 to bytes
bytes := num.Bytes()

// convert byte array to 32bit size words
words := new(Uint32Words)
for i := 0; i < 8; i++ {
// Extract each 32-bit word.
// The binary.BigEndian.Uint32 function reads 4 bytes from the byte slice and converts it to uint32.
words.Words[i] = binary.BigEndian.Uint32(bytes[i*4 : (i+1)*4])
}

return words
}
62 changes: 62 additions & 0 deletions word/word_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package word

import (
"testing"

"github.com/holiman/uint256"
)

func TestToWords(t *testing.T) {
tests := []struct {
name string
hex string // Hexadecimal representation of the uint256 value
expect [8]uint32
}{
{
name: "HalfMaxUint256",
hex: "0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
expect: [8]uint32{
0x7fffffff, 0xffffffff, 0xffffffff, 0xffffffff,
0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
},
},
{
name: "RandomNumber",
hex: "0x1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d6e7f809",
expect: [8]uint32{
0x1a2b3c4d, 0x5e6f7081, 0x92a3b4c5, 0xd6e7f809,
0x1a2b3c4d, 0x5e6f7081, 0x92a3b4c5, 0xd6e7f809,
},
},
{
name: "MaxUint256",
hex: "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
expect: [8]uint32{
0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,
},
},
{
name: "ArbitraryNumber",
hex: "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef",
expect: [8]uint32{
0x12345678, 0x90abcdef, 0x12345678, 0x90abcdef,
0x12345678, 0x90abcdef, 0x12345678, 0x90abcdef,
},
},
}

for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
num, _ := uint256.FromHex(tc.hex)

result := ToWords(num)

for i, word := range result.Words {
if word != tc.expect[i] {
t.Errorf("Test %s failed: word %d is 0x%x, want 0x%x", tc.name, i, word, tc.expect[i])
}
}
})
}
}

0 comments on commit 16b382f

Please sign in to comment.