0

I want to convert an array of uint8_t to a uint32_t in NesC.

Does anyone know how I can do this?

Nouha
  • 33
  • 13
  • I don't know anything about NesC, but should each `uint8_t` in the source array be converted to a single `uint32_t` in the destination? Or should four `uint8_t` in the source be combined to a single `uint32_t` in the destination? – Some programmer dude Sep 19 '12 at 09:14
  • yes this is the idea. Like in C, I want to convert an integer array to one integer. – Nouha Sep 19 '12 at 09:28
  • So, uh, how come you've commented that both Joachim's and my answers are helpful, when they do *different things*? Confusing. – unwind Sep 19 '12 at 10:34

3 Answers3

2

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

Nouha
  • 33
  • 13
0

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];
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

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.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • thanks for the explanation. I used a rong words to explain my need. This can help me a lot. Thank you very much – Nouha Sep 19 '12 at 09:46