简体   繁体   中英

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?

Say I have a byte array (uint8*) with the contents:

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:

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.

#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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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