Is reinterpret_cast safe for this, and is it the best way to do this?
For example, in the code below, I have a class called ibytestream, which allows the reading of uint16_ts and int16_ts from it. ibytestream::next is a vector<unsigned char>::iterator.
inline ibytestream& operator>>(ibytestream& stream, uint16_t& data) {
data = 0;
data |= *stream.next++;
data <<= 8;
data |= *stream.next++;
return stream;
}
inline ibytestream& operator>>(ibytestream& stream, int16_t& data) {
return stream >> reinterpret_cast<uint16_t&>(data);
}
I don't want to duplicate the code for converting the bytes to an integer, so I used reinterpret_cast for the signed version to reuse the code from the unsigned version. It works fine on my machine, but will it work in general on other modern machines?
Yes, this is safe.
Three parts of the standard apply to make this determination: