是否可以通过一次赋值将32位值复制到8位字符的数组中?
假设我有一个包含以下内容的字节数组(uint8*):
01 12 23 45 56 67 89 90
是否可以通过一次赋值(通过强制转换或其他方式)复制到这个数组中?例如,复制类似0x555555的东西,这样我们最终得到:
55 55 55 56 67 78 90
*( (unsigned int *)address_of_byte_buffer) = 0x55555555
注意64位代码下的int大小。。。您将需要找到在两种体系结构下一致为32位的数据类型,例如uint32_t
。
您可以使用reinterpret_cast
,尽管使用时确实需要穿钢制鞋头靴。
#include <vector>
#include <algorithm>
#include <iterator>
#include <iostream>
int main()
{
using std::vector;
using std::copy;
using std::back_inserter;
using std::ostream_iterator;
using std::cout;
int a = 0x55555555;
char* a_begin = reinterpret_cast<char*>(&a);
char* a_end = a_begin + 4;
vector<char> chars;
copy(a_begin, a_end, back_inserter(chars));
copy(chars.begin(), chars.end(), ostream_iterator<int>(cout, ", "));
return 1;
}
输出:
85, 85, 85, 85,
您可以使用reinterpret_cast
将任何内容强制转换为任何内容。
http://msdn.microsoft.com/en-us/library/e0w9f63b(v=vs.80).aspx
您可以使用以下内容:unsigned long* fake_long = reinterpret_cast<unsigned long*> (char_array);
*fake_long = 0x55555555;
但这样的解决方案可以在大型endian机器上运行。为了让它在一个小的endian机器中工作(可能是您想要的),您应该转换长变量的endianness。