I often have the need to take some type and stream it to something as a sequence of character byte values, so I came up with this to accomplish the task:
#include <iostream>
#include <iterator>
/// This provides a way of getting the byte representation of an
/// object of underlying type T.
///
/// This is an alternative to memcopying bytes into a string, stream,
/// character array...
template<typename inT, typename outT = char>
struct byte_streamer
{
byte_streamer(inT ref)
: data(ref)
{}
const inT data;
outT placeholder;
};
template<typename inT, typename outT>
std::ostream& operator<<(std::ostream& strm, const byte_streamer<inT, outT> val)
{
std::copy(reinterpret_cast<const char*>(&val.data),
reinterpret_cast<const char*>(&val.data) + sizeof(inT),
std::ostream_iterator<decltype(val.placeholder)>(strm, ""));
return strm;
}
int main()
{
std::cout << "Here's the bytes of 42 copied directly: " << byte_streamer(42) << std::endl;
std::cout << "Here's the bytes of 42 copied as their numerical values: "
<< byte_streamer<int, int>(42);
}
You can run it online on Coliru or just look at the output here:
Here's the bytes of 42 copied directly: *
Here's the bytes of 42 copied as their numerical values: 42000