简体   繁体   English

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

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

Is it possible to copy a 32 bit value into an array of 8 bit characters with a single assignment? 是否可以通过单个赋值将32位值复制到8位字符的数组中?

Say I have a byte array (uint8*) with the contents: 假设我有一个包含内容的字节数组(uint8 *):

01 12 23 45 56 67 89 90 01 12 23 45 56 67 89 90

Is it possible to copy into this array (through casts or something) with a single assignment? 是否可以通过单个赋值复制到此数组(通过强制转换或其他内容)? For example, copy something like 0x555555, so that we end up with: 例如,复制像0x555555这样的东西,以便最终得到:

55 55 55 55 56 67 78 90 55 55 55 55 56 67 78 90

*( (unsigned int *)address_of_byte_buffer) = 0x55555555

请注意64位代码下int的大小......您需要在两种体系结构下找到一致32位的数据类型,例如uint32_t

You can use reinterpret_cast although you really need to wear steel-toe-capped boots whilst using it. 您可以使用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;
}

Output: 输出:

85, 85, 85, 85, 

You can use reinterpret_cast to cast anything into anything. 您可以使用reinterpret_cast将任何内容转换为任何内容。

http://msdn.microsoft.com/en-us/library/e0w9f63b(v=vs.80).aspx http://msdn.microsoft.com/en-us/library/e0w9f63b(v=vs.80).aspx

You can use something like this: 你可以使用这样的东西:
unsigned long* fake_long = reinterpret_cast<unsigned long*> (char_array); *fake_long = 0x55555555;

But such a solution can work on a big-endian machine. 但是这样的解决方案可以在大端机器上运行。 To make it work in a little-endian machine (probably you want), you should convert endianness of your long variable. 要使它在小端机器(可能是你想要的)中工作,你应该转换长变量的字节顺序。

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

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