将结构转换为字节 [英] Convert struct into bytes

查看:61
本文介绍了将结构转换为字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何在具有Little-endian的处理器上将任何结构转换为字节数组?

How would you convert any struct into byte array on processors with little-endian?

推荐答案

您可以使用 char * 来访问C ++中的任何类型的对象,因此:

You can use a char* to access any type of object in C++, so:

struct S
{
    int a;
    int b;
    // etc.
};

S my_s;

char* my_s_bytes = reinterpret_cast<char*>(&my_s);

// or, if you prefer static_cast:
char* my_s_bytes = static_cast<char*>(static_cast<void*>(&my_s));

(至少有一些辩论 reinterpret_cast static_cast 的正确性;实际上并不重要-两者都应产生相同的结果)

(There is at least some debate over the correctness of the reinterpret_cast vs. the static_cast; in practice it doesn't really matter--both should yield the same result)

这篇关于将结构转换为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆