I'm trying to find a Qt function that can convert bytes to int with the same endianness that I'm using below. I feel like I'm definitely reinventing the wheel here, and that there must be something in the Qt libs to do this already. Does it exist?
// TODO: qt must have a built in way of converting bytes to int.
int IpcReader::bytesToInt(const char *buffer, int size)
{
if (size == 2) {
return
(((unsigned char)buffer[0]) << 8) +
(unsigned char)buffer[1];
}
else if (size == 4) {
return
(((unsigned char)buffer[0]) << 24) +
(((unsigned char)buffer[1]) << 16) +
(((unsigned char)buffer[2]) << 8) +
(unsigned char)buffer[3];
}
else {
// TODO: other sizes, if needed.
return 0;
}
}
// TODO: qt must have a built in way of converting int to bytes.
void IpcClient::intToBytes(int value, char *buffer, int size)
{
if (size == 2) {
buffer[0] = (value >> 8) & 0xff;
buffer[1] = value & 0xff;
}
else {
// TODO: other sizes, if needed.
}
}
Edit: The data is always big endian (no matter what OS), so for example 101 would be [0, 0, 0, 101] and 78000 is [0, 1, 48, 176].
std::memcpy?ntohlandntohsare for.