Skip to content

Commit

Permalink
Merge pull request #106 from chfast/as_bytes
Browse files Browse the repository at this point in the history
intx: Add as_bytes() helper for casting intx to bytes
  • Loading branch information
chfast authored Aug 14, 2019
2 parents 9b55d9d + c65a233 commit 9312a4c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
12 changes: 12 additions & 0 deletions include/intx/intx.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,18 @@ constexpr const uint64_t* as_words(const uint<N>& x) noexcept
return as_words(x.lo);
}

template <unsigned N>
inline uint8_t* as_bytes(uint<N>& x) noexcept
{
return reinterpret_cast<uint8_t*>(as_words(x));
}

template <unsigned N>
inline const uint8_t* as_bytes(const uint<N>& x) noexcept
{
return reinterpret_cast<const uint8_t*>(as_words(x));
}

/// Implementation of shift left as a loop.
/// This one is slower than the one using "split" strategy.
template <unsigned N>
Expand Down
16 changes: 15 additions & 1 deletion test/unittests/test_intx.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -490,4 +490,18 @@ TYPED_TEST(uint_test, to_string_base)
EXPECT_EQ(to_string(x, 36), "sg");
EXPECT_EQ(to_string(x, 2), "10000000000");
EXPECT_EQ(to_string(x, 8), "2000");
}
}

TYPED_TEST(uint_test, as_bytes)
{
constexpr auto x = TypeParam{0xa05};
const auto b = as_bytes(x);
EXPECT_EQ(b[0], 5);
EXPECT_EQ(b[1], 0xa);

auto y = x;
auto d = as_bytes(y);
d[0] = 3;
d[1] = 0xc;
EXPECT_EQ(y, 0xc03);
}

0 comments on commit 9312a4c

Please sign in to comment.