Conversion of unsigned to signed int

Hi Guys,

I'm having some trouble converting unsigned ints to signed ones.

In my system I am sending serial data to an arduino from a computer. I send a 4 byte command
which is
[ 0 ] 'p' or 's' for position or speed
[ 1 ] pos/speed high byte
[ 2 ] pos/speed low byte
[ 3 ] flag for +ve or -ve

my receiving code on the arduino is:

uint8_t writeval = 1;
uint8_t dir = 0;
uint8_t inputArray[5];
int targetPos = 0;
void loop()   
{
int n =0;
if(Serial.available())
{
  delayMicroseconds(5000);
while (Serial.available()) {
   

    inputArray[n] = Serial.read(); 
   
     n++;
     delayMicroseconds(500);

  }

  
   targetPos = 0;
 
    dir = inputArray[3];
    
    if((dir&0x01))
    {
    targetPos=static_cast<int>(((uint16_t)inputArray[2])+((uint16_t)(inputArray[1]<<8)))*1;
    }
    
    if(!(dir&0x01))
    {
    targetPos=static_cast<int>(((uint16_t)inputArray[2])+((uint16_t)(inputArray[1]<<8)))*-1;
    }
    Serial.println(targetPos);

  Serial.println(static_cast<int>((uint16_t)(inputArray[1]<<8)));
Serial.println(enc.read()); 
 Serial.println("");
 
}

Sending:

70 255 253 00
as in position -65533
Gives:

-3
-256
0

Sending:

70 255 253 01
as in position 65533
Gives:

3
-256
0

So it looks like its using the unisgned ints as signed ints in twos compliment. Any pointers?

Thanks

I think you are shifting a byte.

You can use as many variables and as many lines of code as you like. Let the compiler take care of it.

I'm not sure how a negative number will be converted, when the 'word' is cast to 'int'. I'm not sure about the format either. Can the 16-bit number be from 0x0000 to 0xFFFF and also be negative ? Perhaps you need a long to store it.

int hibyte = inputArray[1];
int lowbyte = inputArray[2];
word posspeed = word (hibyte, lowbyte);
int nps = (int) posspeed;

if(!(dir&0x01))
  nps = -nps;

Thanks for the help, it almost worked, but i changed it to

	int hibyte = inputArray[1];
int lowbyte = inputArray[2];
word posspeed = word (hibyte, lowbyte);
long targetPos = (long) posspeed;

if(!(dir&0x01))
{
  targetPos = -targetPos;
  
}

and now its great. I realise the error of my ways now, even though I knew the data being sent wouldn't get much above 1000 the compiler didn't. sticking the int into a long meant I had enough bits to do twos compliment, it meant I lose a couple of byte ram but meh.

But neither -65533 nor 65533 fit in a signed 16 bit int, you'll need a long
to represent them.