Implement Uint::to_be_bytes()

This commit is contained in:
Nadav Ivgi 2020-12-29 20:46:21 +02:00
parent c9c2e452e2
commit 3761b0d808
2 changed files with 22 additions and 0 deletions

View File

@ -54,6 +54,7 @@ macro_rules! define_le_to_array {
define_slice_to_be!(slice_to_u32_be, u32); define_slice_to_be!(slice_to_u32_be, u32);
define_slice_to_be!(slice_to_u64_be, u64); define_slice_to_be!(slice_to_u64_be, u64);
define_be_to_array!(u32_to_array_be, u32, 4); define_be_to_array!(u32_to_array_be, u32, 4);
define_be_to_array!(u64_to_array_be, u64, 8);
define_slice_to_le!(slice_to_u16_le, u16); define_slice_to_le!(slice_to_u16_le, u16);
define_slice_to_le!(slice_to_u32_le, u32); define_slice_to_le!(slice_to_u32_le, u32);
define_slice_to_le!(slice_to_u64_le, u64); define_slice_to_le!(slice_to_u64_le, u64);

View File

@ -102,6 +102,17 @@ macro_rules! construct_uint {
$name(slice) $name(slice)
} }
/// Convert a big integer into a byte array using big-endian encoding
pub fn to_be_bytes(&self) -> [u8; $n_words * 8] {
use super::endian::u64_to_array_be;
let mut res = [0; $n_words * 8];
for i in 0..$n_words {
let start = i * 8;
res[start..start+8].copy_from_slice(&u64_to_array_be(self.0[$n_words - (i+1)]));
}
res
}
// divmod like operation, returns (quotient, remainder) // divmod like operation, returns (quotient, remainder)
#[inline] #[inline]
fn div_rem(self, other: Self) -> (Self, Self) { fn div_rem(self, other: Self) -> (Self, Self) {
@ -505,6 +516,16 @@ mod tests {
Uint256([0x11fed2bad1c0ffe0, 0xbaadf00ddefaceda, 0xdeafbabe2bedfeed, 0x1badcafedeadbeef])); Uint256([0x11fed2bad1c0ffe0, 0xbaadf00ddefaceda, 0xdeafbabe2bedfeed, 0x1badcafedeadbeef]));
} }
#[test]
pub fn uint_to_be_bytes() {
assert_eq!(Uint128([0xdeafbabe2bedfeed, 0x1badcafedeadbeef]).to_be_bytes(),
[0x1b, 0xad, 0xca, 0xfe, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xaf, 0xba, 0xbe, 0x2b, 0xed, 0xfe, 0xed]);
assert_eq!(Uint256([0x11fed2bad1c0ffe0, 0xbaadf00ddefaceda, 0xdeafbabe2bedfeed, 0x1badcafedeadbeef]).to_be_bytes(),
[0x1b, 0xad, 0xca, 0xfe, 0xde, 0xad, 0xbe, 0xef, 0xde, 0xaf, 0xba, 0xbe, 0x2b, 0xed, 0xfe, 0xed,
0xba, 0xad, 0xf0, 0x0d, 0xde, 0xfa, 0xce, 0xda, 0x11, 0xfe, 0xd2, 0xba, 0xd1, 0xc0, 0xff, 0xe0]);
}
#[test] #[test]
pub fn uint256_arithmetic_test() { pub fn uint256_arithmetic_test() {
let init = Uint256::from_u64(0xDEADBEEFDEADBEEF).unwrap(); let init = Uint256::from_u64(0xDEADBEEFDEADBEEF).unwrap();