encoding/bigint: allow to convert unsigned integers

Signed-off-by: Evgeniy Stratonikov <evgeniy@nspcc.ru>
This commit is contained in:
Evgeniy Stratonikov 2021-07-14 15:05:30 +03:00
parent 3a4e0caeb8
commit 9c5b4e5916
2 changed files with 33 additions and 0 deletions

View file

@ -4,6 +4,8 @@ import (
"encoding/binary" "encoding/binary"
"math/big" "math/big"
"math/bits" "math/bits"
"github.com/nspcc-dev/neo-go/pkg/util"
) )
const ( const (
@ -13,6 +15,12 @@ const (
wordSizeBytes = bits.UintSize / 8 wordSizeBytes = bits.UintSize / 8
) )
// FromBytesUnsigned converts data in little-endian format to an unsigned integer.
func FromBytesUnsigned(data []byte) *big.Int {
bs := util.ArrayReverse(data)
return new(big.Int).SetBytes(bs)
}
// FromBytes converts data in little-endian format to // FromBytes converts data in little-endian format to
// an integer. // an integer.
func FromBytes(data []byte) *big.Int { func FromBytes(data []byte) *big.Int {

View file

@ -122,6 +122,31 @@ func TestBytesToInt(t *testing.T) {
}) })
} }
var unsignedCases = []struct {
number int64
buf []byte
}{
{0xff00000000, []byte{0x00, 0x00, 0x00, 0x00, 0xff}},
{0xfd00000000, []byte{0x00, 0x00, 0x00, 0x00, 0xfd}},
{0x8000000000, []byte{0x00, 0x00, 0x00, 0x00, 0x80}},
{0xff0200000000, []byte{0x00, 0x00, 0x00, 0x00, 0x02, 0xff}},
{0xff0100000000, []byte{0x00, 0x00, 0x00, 0x00, 0x01, 0xff}},
{0xff0100000000, []byte{0x00, 0x00, 0x00, 0x00, 0x01, 0xff, 0x00}},
}
func TestBytesToUnsigned(t *testing.T) {
for _, tc := range testCases {
if tc.number > 0 {
num := FromBytesUnsigned(tc.buf)
assert.Equal(t, tc.number, num.Int64(), "expected %x, got %x", tc.number, num.Int64())
}
}
for _, tc := range unsignedCases {
num := FromBytesUnsigned(tc.buf)
assert.Equal(t, tc.number, num.Int64(), "expected %x, got %x", tc.number, num.Int64())
}
}
func TestEquivalentRepresentations(t *testing.T) { func TestEquivalentRepresentations(t *testing.T) {
for _, tc := range testCases { for _, tc := range testCases {
buf := tc.buf buf := tc.buf