I am trying to convert a signed integer to byte array.
I tried below code. In this eg, expected result is FD 53
for the input -685
(2s complement form).
int exponent = -685;
std::int64_t const exponent_range{std::labs(exponent * (int64_t)2)};
std::uint8_t const exponent_bytes{static_cast<std::uint8_t>((std::log2(static_cast<double>(exponent_range)) / 8.0) + 1.0)};
std::vector<std::uint8_t> bytes;
for (std::uint8_t i = exponent_bytes; i > 0; --i) {
bytes.push_back(static_cast<std::uint8_t>((exponent >> ((i - 1U) * 8)) & 0xFFU));
}
In the last line I am shifting a signed integer to the right. Is this standard compliant operation or undefined behavior?
Kindly suggest any alternate standard compliant(C99 or C++11) implementation. I need a solution that would work in both byte orderings.