PLC Programming HandbooksPopular ArticlesNavigationUser login |
When Being Negative is a ComplementLet's delve deeper into PLC programming by considering again our common word made of 16 bits. If it was all filled up with one's then the decimal value would be 65535. So a range from 0 to 65535 could be represented. Adding binary numbers together would be very similar to addition in decimal. For example 0 + 1 = 1 and 1 + 1 = 10 (carry the one). The problem comes when you need to subtract. How do you represent a negative number when you can't just put a minus sign in front of it and say it's good? Remember that the computer can only do a 0 or a 1. To our rescue comes a concept called taking the complement. Complement's are a pretty cool trick and you can learn more about them at Wikipedia. We'll keep it simple here and talk about two's complement which is the most common in computers and PLCs. Signed binary numbers are achieved by stealing the 16th bit in a word (the most significant bit) and using that as a sign bit where 0 is positive and 1 is negative.
By doing this we have shifted the range of values from 0 to 65535 to -32767 to +32767. So the high end of our value is decreased but we've made it a whole lot easier to indicate a negative number and do subtraction. Here's how it works. Let's take a number like 30 and perform the two's complement to get -30.
In the PLC then the value of -30 will be respresented as 1111 1111 1110 0010. Maybe not what you would expect? The beauty of this is that now all the processor has to worry about is adding the two numbers to get the correct value. See how this magically works in the table below (I'm just going to use 8 bits now to simplify things but it works just the same with however many bits you want).
For the most part this will all work seamlessly in the background while you program away. It's just that every once in awhile you'll need this knowledge to overcome any limitations in the system. Dealing with negative numbers can be pretty tricky but with complements like this you better not let it go to your head. |
Thanks
Thank you. A article well written. I have read a lot of books regarding PLCs...but let me tell you, no one has put it this way...:) The writing style is easy to grasp, off-beat, and really appeals to the reader in a very unconventional manner. Thanks again.
Appreciation of your site
Thank you very much for the easy to grasp explanation of the basics for simatic! Too bad this was not the case during school, hence a great refreshment for me. I will definitely recommend this site to anyone wanting to learn more about plc programming.