I want to convert an array of uint8_t
to a uint32_t
in NesC.
Does anyone know how I can do this?
I want to convert an array of uint8_t
to a uint32_t
in NesC.
Does anyone know how I can do this?
The solution that i were found is the use of the function :
void * memcpy ( void * destination, const void * source, size_t num );
There is also the function :
void * memset ( void * ptr, int value, size_t num );
In my code i use memcpy and it works fine. Thanks to all people that answer my question
If you want to convert a single uint8_t
in the source to a single uint32_t
in the destination, it's actually very simple. Just create the destination array, and copy the values in a loop:
uint8_t *source;
size_t source_count; /* Number of entries in the source */
uint32_t *dest = malloc(sizeof(*dest) * source_count);
for (int i = 0; i < source_count; i++)
dest[i] = source[i];
Your title mentions strings, but your question text doesn't. This is confusing.
If you have four 8-bit integers, you can join them into a single 32-bit like so:
const uint8_t a = 1, b = 2, c = 3, d = 4;
const uint32_t big = (a << 24) | (b << 16) | (c << 8) | d;
This orders them like so, where letters denote bits from the variables above:
0xaabbccdd
In other words, a
is taken to be the most significant byte, and d
the least.
If you have an array, you can of course do this in a loop:
uint32_t bytes_to_word(const uint8_t *bytes)
{
size_t i;
uint32_t out = 0;
for(i = 0; i < 4; ++i)
{
out <<= 8;
out |= bytes[i];
}
return out;
}
The above assumes that bytes
has four values.