Question
What is the best way to convert binary to integral representation?
Context
Imagine that we have a buffer containing binary data received from an external source, such as a socket connection or a binary file. The data is organized in a well-defined format, and we know that the first four octets represent a single unsigned 32-bit integer (which may be the size of the following data). What would be a more efficient way to hide these octets in a usable format (e.g. std :: uint32_t)?
Example
Here is what I have tried so far:
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstring>
#include <iostream>
int main()
{
std::array<char, 4> buffer = { 0x01, 0x02, 0x03, 0x04 };
std::uint32_t n = 0;
n |= static_cast<std::uint32_t>(buffer[0]);
n |= static_cast<std::uint32_t>(buffer[1]) << 8;
n |= static_cast<std::uint32_t>(buffer[2]) << 16;
n |= static_cast<std::uint32_t>(buffer[3]) << 24;
std::cout << "Bit shifting: " << n << "\n";
n = 0;
std::memcpy(&n, buffer.data(), buffer.size());
std::cout << "std::memcpy(): " << n << "\n";
n = 0;
std::copy(buffer.begin(), buffer.end(), reinterpret_cast<char*>(&n));
std::cout << "std::copy(): " << n << "\n";
}
On my system, the result of the following program is
Bit shifting: 67305985
std::memcpy(): 67305985
std::copy(): 67305985
- Are they all standard compatible or do they use the behavior defined by the implementation?
- Which one is more effective?
- ?