Strange result for concatenation operation

Hello,

I want to concatenate two neighbouring values in an 1-D Array , for this i used the provided example code but i keep getting strange results .

int x=payloadData[2]; //
int y=payloadData[3]; //
//The first byte of the Value represents the high-order bits of the twos-compliment value, while the second byte represents //the low-order bits
// the original number has a range of -32768 to 32767

x<<=8;
x|=y;

Serial.println(" val_BIN: “);
Serial.println(x, BIN);
Serial.println(” val_DEC: “);
Serial.println(x ,DEC);
Serial.println(” val_HEX: ");
Serial.println(x ,HEX);

i also tried this

// int z = y|(x<< 8 );
Serial.println(" val_BIN: “);
Serial.println(z,BIN);
Serial.println(” val_DEC: “);
Serial.println(z,DEC);
Serial.println(” val_HEX: ");
Serial.println(z,HEX);

I displayed the result in this 3 modes in order to see what’s happening

For example if x = 11110000
y = 1 1 1 1 1 1 1 1

In Binary it displayes this : 1111111111111111 1111000011111111 // i do get x concatenated with y but it also containes 2 bytes of "ones " as a header
In HEX i get the correct result F0FF
In DEC i get some negative numbers…

Can somenone figure out what am i missing ?

0xf0ff as an int is a negative number.
There is no problem. If you want it represented as positive, use an unsigned representation.

why is it printing 32 binary digits there ? Is that the code you actually used.

The negative result you are getting, would appear to be correct.

@ Groove

I know that , due to the number's original integer range of values , it can be negative , but how did you figure it out ? Those 2 bytes of digits tell me that i have a negative number ? 0xf0ff is just an example , i'm receiving this format for almost any number , except when The High Byte is 0x0000

@ michinyon

Yes this is the code that i actually used , i tryed both codes with the same result , but if you both say that it's correct , thank you But i still don't know how to recognise negative numbers.

In standard 2’s complement binary, a negative number will have the MSB set to 1.

I took a peek at the conversion routine used by the arduino (Print::printNumber). It converts from a long, which is 32 bits, and as you are using a negative number, the cast "adds" a couple of 1's to make the value correct (as a long). Unfortunately, your code will only work for positive numbers. If you want to make the negative numbers print correctly as 16 bit values, you must write your own conversion routine (or grab one off the internet, there's plenty of them about).

Pieter

pbrouwer: the cast "adds" a couple of 1's to make the value correct (as a long).

Otherwise known as "sign extension".