【问题标题】:c++ - store byte[4] in an intc++ - 将字节 [4] 存储在 int 中
【发布时间】:2014-11-30 06:43:08
【问题描述】:

我想取一个包含 4 个字节的字节数组,并将其存储在一个 int 中。

例如(非工作代码):

unsigned char _bytes[4];
int * combine;
_bytes[0] = 1;
_bytes[1] = 1;
_bytes[2] = 1;
_bytes[3] = 1;
combine = &_bytes[0];

我不想使用位移将字节放入 int,我想指向字节内存并尽可能将它们用作 int。

【问题讨论】:

  • 不,你不能。字节顺序未知,只有位移才能保证
  • 好吧,如果您想在运行时确定主机系统的字节序,那么这会很有用。

标签: c++ int byte type-conversion


【解决方案1】:

在标准 C++ 中,不可能可靠地做到这一点。严格的别名规则说,当您阅读int 类型的表达式时,它必须实际指定一个int 对象(或const int 等),否则会导致未定义的行为。

但是你可以做相反的事情:声明一个int,然后填写字节:

int combine;
unsigned char *bytes = reinterpret_cast<unsigned char *>(&combine);
bytes[0] = 1;
bytes[1] = 1;
bytes[2] = 1;
bytes[3] = 1;

std::cout << combine << std::endl;

当然,您从中获得的哪个值取决于您的系统如何表示整数。如果您希望您的代码在不同系统上使用相同的映射,那么您不能使用内存别名;您必须改用方程式。

【讨论】:

  • 值得注意的是,这也避免了任何对齐问题。
  • 这很完美,因为您可以修改combine,这样做还会更改各个字节中的值。谢谢。
猜你喜欢
  • 2020-03-01
  • 1970-01-01
  • 2017-05-19
  • 1970-01-01
  • 2021-09-15
  • 1970-01-01
  • 2011-04-16
  • 1970-01-01
  • 2012-02-08
相关资源
最近更新 更多