Convert char to short

ANIMATEK picture ANIMATEK · Sep 11, 2014 · Viewed 10.7k times · Source

I need to copy the data from 2 char (8 bit long) to a single short (16 bit long). I tried two different ways, but can't get it to work.

void char2short(char* pchar, short* pshort)
{
    memcpy(pshort    , pchar + 1    , 1);
    memcpy(pshort + 1, pchar    , 1);
}

And the other one:

void char2short(char* pchar, short* pshort)
{
   short aux;
   aux = ((*pchar & 0x00FF) << 8) | ((*(pchar+1) & 0xFF00) >> 8);
   *pshort = aux;
}

Answer

mch picture mch · Sep 11, 2014
#include <stdio.h>


void char2short(unsigned char* pchar, unsigned short* pshort)
{
  *pshort = (pchar[0] << 8) | pchar[1];
}

int main()
{
  unsigned char test[2];
  unsigned short result = 0;

  test[0] = 0xAB;
  test[1] = 0xCD;
  char2short(test, &result);
  printf("%#X\n",result);
  return 0;
}

this will do the job.