Go Down

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

#### dmurray14

##### Oct 28, 2009, 10:29 pm
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

#1
##### Oct 28, 2009, 10:37 pm
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

#2
##### Oct 29, 2009, 06:26 am
Gotcha, thanks. I'll give it a go...

#### Grumpy_Mike

#3
##### Oct 29, 2009, 10:40 pm
Quote
that sends a number in two bits.

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

#### retrolefty

#4
##### Oct 30, 2009, 04:44 am
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

#5
##### Nov 04, 2009, 06:24 am
I'm an idiot, that was a typo. Should have been two BYTES. I assume that changes things?

#6
##### Nov 04, 2009, 06:54 am
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 pmLast Edit: Nov 04, 2009, 03:24 pm by dmurray14 Reason: 1
Cool, so something like this would work?

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

Thanks!

#8
##### Nov 04, 2009, 10:44 pmLast 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

#9
##### Nov 05, 2009, 12:18 am
Perfect, thanks! Still learning

Go Up