Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 393
Verhogen Avatar asked Dec 30 '25 22:12

Verhogen


2 Answers

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

Beware of the size of int under 64-bit code... you will need to find a data type that is consistently 32 bits under both architectures, such as uint32_t.

like image 124
JTeagle Avatar answered Jan 02 '26 14:01

JTeagle


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, 
like image 35
Peter Wood Avatar answered Jan 02 '26 13:01

Peter Wood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!