考虑以下 C++ 代码:
unsigned char* data = readData(..); //Let say data consist of 12 characters
unsigned int dataSize = getDataSize(...); //the size in byte of the data is also known (let say 12 bytes)
struct Position
{
float pos_x; //remember that float is 4 bytes
double pos_y; //remember that double is 8 bytes
}
现在我想用数据填充位置变量/实例。
Position pos;
pos.pos_x = ? //data[0:4[ The first 4 bytes of data should be set to pos_x, since pos_x is of type float which is 4 bytes
pos.pos_x = ? //data[4:12[ The remaining 8 bytes of data should be set to pos_y which is of type double (8 bytes)
我知道在data
中,第一个字节对应于pos_x
,其余字节对应于pos_y
。这意味着数据的第 4 个字节/字符应该用于填充 pos_x,其余 8 个字节填充 pos_y
但我不知道该怎么做。
任何想法?谢谢。 ps:我限于c++11
最佳答案
您可以使用普通的 memcpy
作为另一个答案的建议。我建议将 memcpy
打包到一个函数中,该函数还可以为您进行错误检查,以实现最方便和类型安全的使用。
例子:
#include <cstring>
#include <stdexcept>
#include <type_traits>
struct ByteStreamReader {
unsigned char const* begin;
unsigned char const* const end;
template<class T>
operator T() {
static_assert(std::is_trivially_copyable<T>::value,
"The type you are using cannot be safely copied from bytes.");
if(end - begin < static_cast<decltype(end - begin)>(sizeof(T)))
throw std::runtime_error("ByteStreamReader");
T t;
std::memcpy(&t, begin, sizeof t);
begin += sizeof t;
return t;
}
};
struct Position {
float pos_x;
double pos_y;
};
int main() {
unsigned char data[12] = {};
unsigned dataSize = sizeof data;
ByteStreamReader reader{data, data + dataSize};
Position p;
p.pos_x = reader;
p.pos_y = reader;
}
关于c++ - 将(n 个第一个字节的)unsigned char 指针转换为 float 和 double C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52410302/