Reputation: 28631
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
Upvotes: 3
Views: 7615
Reputation: 2196
*( (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
.
Upvotes: 4
Reputation: 327
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.
Upvotes: 0
Reputation: 24153
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,
Upvotes: 1
Reputation: 11787
You can use reinterpret_cast
to cast anything into anything.
http://msdn.microsoft.com/en-us/library/e0w9f63b(v=vs.80).aspx
Upvotes: 0