Two’s complement and the Arduino

I’ve written about Two’s complement before in my posts about the Package Tracker. Just yesterday, I had cause to write a two’s complement function for the Arduino. I needed to evaluate a byte of two’s complement data and send it out the serial port as an ascii coded signed integer.
A signed integer byte can have a value between -128 and +127. I found that it was easier to manipulate the data on the Arduino rather than futz with the raw two’s complement number in MSExcel or MSAccess. Also this was a good way to acquaint myself with the Arduino’s bitwise operators. This was easier than I expected and I had the function done in no time.

void PrintSignedNumber(byte twoscomp){
  if (twoscomp & B10000000){
    twoscomp = (twoscomp ^ B11111111 )+1;
    Serial.print(twoscomp, DEC);
    Serial.print(PSTR(" "));  
    Serial.print(twoscomp, DEC);

The routine checks the MSB of the twoscomp variable. If the MSB is set, this indicates that twoscomp is a negative number. If the MSB is zero, then twoscomp is a positive number. Positive numbers are easily dealt with. Print a space and then print the byte as its ascii representation in decimal format.

Negative numbers require a slight bit of manipulation to become easily readable. First print a negative sign. Then get the ones complement of the twoscomp variable by performing an exclusive or to the twoscomp variable. Two’s complement is one’s complement plus one, so next add 1 to the twoscomp variable to make a two’s complement of the original. Finally, print the the twoscomp byte as its ascii representation in decimal format.

If you are a programming pro, this may have been obvious. If you are a hobbyist, I hope this explanation is helpful.


~ by ratdad on March 4, 2009.

One Response to “Two’s complement and the Arduino”

  1. It is helpful for the hobbist 🙂 Thanks!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: