char array to unsigned short array

How can i easely convert or use a char array to a unsigned short array

i have
char color[76801];

this needs to be converted (altered or something else) to
unsinged short image[???]

how can this be done ?

On an arduino, I doubt that it can. An unsigned short occupies two bytes and an array of that size wouldn't even fit on a mega. On a machine with more memory, a simple for loop would suffice. From the names, you imply that you're trying to do some image processing. Generally, the arduino has too little memory and is too slow for such applications.

I know,

array char color[76801];
is the doubled size of the image, isn't there a way to make the image points to the memory location of color

so when i do image[0] i use color[0] +color[1]

You can use a pointer and point it to your existing array thus:

char image[10];
unsigned short *im = (unsigned short*)image;

And then operate using the pointer instead. You may have endian issues to overcome though.

Could there be something wrong when doing this.

Becaus i should get a red collor and on the screen it apears in blue.

when i read image[0] and image[1] the values indicate red, but after painting the image it's partial blue.
what could be wrong ?

Could there be something wrong when doing this.

Yes, I imagine there could be something wrong when doing this.
Whatever "this" is. (Hint)

It could be that your color data is in big endian order and needs to be converted to the Atmel little endian order.

Because you want to copy the content of one index to another, you should only increment each pointer by the size of its type. I’ve seen this done with the ‘++’ operator. One thing you can try just to get a feel for how this works is below.

void copy_char(char* color, unsigned short* image)
{
  while(*color)
  {
    *image = *color;
    image++;
    color++;
  }
}

int main(void)
{
  char happy[] = "Happy was the song of the summer.";
  unsigned short traslation[sizeof(happy)];
  
  printf("Original message: %s\n", happy);
  copy_char(happy, traslation);
  
  int i;
  for(i = 0; i < strlen(happy); i++)
  {
    printf("%u ", traslation[i]);
  }
  puts("");
  for(i = 0; i < strlen(happy); i++)
  {
    printf("%c", traslation[i]);
  }
  puts("");
  
  return 0;
}

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.