Go Down

Topic: Twos complement? (Read 10628 times) previous topic - next topic

dmurray14

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!

retrolefty

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.

http://en.wikipedia.org/wiki/Twos_complement

Lefty


dmurray14

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

Grumpy_Mike

Quote
that sends a number in two bits.


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

retrolefty

Quote
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  ;)

Lefty

dmurray14

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

Coding Badly

Quote
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.

dmurray14

#7
Nov 04, 2009, 03:23 pm Last Edit: Nov 04, 2009, 03:24 pm by dmurray14 Reason: 1
Cool, so something like this would work?
       

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

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

Thanks!

Coding Badly

#8
Nov 04, 2009, 10:44 pm Last Edit: Nov 04, 2009, 10:45 pm by bcook Reason: 1
Quote
so something like this would work?

Almost...

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

Code: [Select]
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.

dmurray14

Perfect, thanks! Still learning ;)

Go Up