c++ - 将(n 个第一个字节的)unsigned char 指针转换为 float 和 double C++

标签 c++ c++11 pointers

考虑以下 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/

相关文章:

c++ - 如何在C++中使用DirectShow渲染音频

c++ - 如何将字符串从 C# 传递到 C++ 并指定编码

c++ - 分配默认值 std::function

c - int 指针指向两个结构体指针?

c++ - 为什么不从 std::allocator 继承

c++ - 警告 : suggest parentheses around assignment while (*(arg_to++) = *(arg_from++));

C++ 语法 : default and delete modifiers

c++ - 在函数返回中返回新分配的 shared_ptr 的引用是否合法?

C指针段错误

c - C 中的优先级队列链表实现 - enqueue() 操作失败