Twos complement?

Hey guys,

I'm still pretty new at this. I'm working on accepting data from a module that sends a number in two bits. I'm told it is positive or negative according to two's complement. While I understand the concept, what do I have to do with the arduino to go from a two-bit two's complement number to an int?

Thanks!

The signed int variables used in Arduino already uses twos complement for negative numbers. To convert a positive number to a negative number in twos complement you invert all the bits and add 1.

I think to convert a 2 bit signed number to a 16 bit signed number you just have to set the extra 14 higher bits to one if the second bit of the smaller number is a one, but not really sure.

Lefty

Gotcha, thanks. I'll give it a go...

that sends a number in two bits.

Do you mean two parts or two binary bits? Lefty was talking about the latter.

Do you mean two parts or two binary bits? Lefty was talking about the latter.

Yes, I did take it as posted literally, as 2 bits, which on the surface is kind of silly I would think, the range would be rather restrictive, no :wink:

Lefty

I'm an idiot, that was a typo. Should have been two BYTES. I assume that changes things?

what do I have to do with the arduino to go from a two-byte two's complement number to an int?

Nothing. On the Arduino a two-byte two's-complement number is an int. Just make certain you get the bytes in the correct order and you're good-to-go.

Cool, so something like this would work?

plMSB = Serial1.read();
plLSB = Serial1.read();

myInt = (int)plMSB<<8;
myInt+= plLSB;

Thanks!

so something like this would work?

Almost...

You should get in the habit of using a bitwise-or instead of addition when combining bytes...

myInt = (int)plMSB<<8;
myInt |= plLSB;

I don't think it's a problem in this case but there are times when using addition leads to a sign extension and that can cause problems.

Perfect, thanks! Still learning :wink: