繁体   English   中英

C ++将32位整数复制到字节数组中

[英]C++ Copy 32-bit Integer into byte array

是否可以通过单个赋值将32位值复制到8位字符的数组中?

假设我有一个包含内容的字节数组(uint8 *):

01 12 23 45 56 67 89 90

是否可以通过单个赋值复制到此数组(通过强制转换或其他内容)? 例如,复制像0x555555这样的东西,以便最终得到:

55 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;

但是这样的解决方案可以在大端机器上运行。 要使它在小端机器(可能是你想要的)中工作,你应该转换长变量的字节顺序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM