Continue to Site

Welcome to our site!

Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

  • Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

Efficient 2s complement in C

Status
Not open for further replies.

edeca

Active Member
I'm looking at some I2C temperature sensors that return data in 2s complement. The format is 2 bytes:

SIGN | 2^7 | 2^6 | ... | 2^0 | 2^-1 | ... | 2^-4 | 0 | 0 | 0

This can give steps of 0.0625 if the sensor ADC is run in 13 bit mode. The 3 least significant bits are always 0.

I can think of a few ways of converting this to a number for display, but I haven't found any that seem particularly efficient.

It seems the complete DIY way would involve bit flipping if the SIGN is set followed by shifting the integer parts right so they line up with a single byte. The decimal part could be calculated manually by adding 0.5/0.25/0.125/0.0625 for each bit that is set.

I'm aiming code at an 18F, can anybody spot the easy way which I must have missed? Or am I on the right track?

(The sensor is a DS620, accurate to 0.5C)
 
...would involve bit flipping if the SIGN is set ...
That would OK if it was 1's-complement, but not for 2's-comp. Just use the negation operator (i.e. if(temp < 0)temp = -temp;).
 
Have a read of this thread. In it we discuss printing the fractional part of an 8.4 number. The same technique could easily be implemented in C.

Mike.
 
Thanks guys.

The DS18B20 code is fantastic, roughly what I had intended to do (once I'd ironed it out) so I can adapt that for my needs. I don't have the sensors yet so I'll write some test code and use known values from the datasheet.

Pommie, your code is crazy. I need some of what you're drinking, that is so elegant and tiny.
 
Status
Not open for further replies.

Latest threads

New Articles From Microcontroller Tips

Back
Top