Skip to content

Commit 9312a4c

Browse files
authored
Merge pull request #106 from chfast/as_bytes
intx: Add as_bytes() helper for casting intx to bytes
2 parents 9b55d9d + c65a233 commit 9312a4c

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

include/intx/intx.hpp

+12
Original file line numberDiff line numberDiff line change
@@ -434,6 +434,18 @@ constexpr const uint64_t* as_words(const uint<N>& x) noexcept
434434
return as_words(x.lo);
435435
}
436436

437+
template <unsigned N>
438+
inline uint8_t* as_bytes(uint<N>& x) noexcept
439+
{
440+
return reinterpret_cast<uint8_t*>(as_words(x));
441+
}
442+
443+
template <unsigned N>
444+
inline const uint8_t* as_bytes(const uint<N>& x) noexcept
445+
{
446+
return reinterpret_cast<const uint8_t*>(as_words(x));
447+
}
448+
437449
/// Implementation of shift left as a loop.
438450
/// This one is slower than the one using "split" strategy.
439451
template <unsigned N>

test/unittests/test_intx.cpp

+15-1
Original file line numberDiff line numberDiff line change
@@ -490,4 +490,18 @@ TYPED_TEST(uint_test, to_string_base)
490490
EXPECT_EQ(to_string(x, 36), "sg");
491491
EXPECT_EQ(to_string(x, 2), "10000000000");
492492
EXPECT_EQ(to_string(x, 8), "2000");
493-
}
493+
}
494+
495+
TYPED_TEST(uint_test, as_bytes)
496+
{
497+
constexpr auto x = TypeParam{0xa05};
498+
const auto b = as_bytes(x);
499+
EXPECT_EQ(b[0], 5);
500+
EXPECT_EQ(b[1], 0xa);
501+
502+
auto y = x;
503+
auto d = as_bytes(y);
504+
d[0] = 3;
505+
d[1] = 0xc;
506+
EXPECT_EQ(y, 0xc03);
507+
}

0 commit comments

Comments
 (0)