Hacker News new | past | comments | ask | show | jobs | submit login
Representating negative numbers in computers: 2's complement (embedded.fm)
4 points by ingve on March 20, 2016 | hide | past | favorite | 2 comments



There are a few ways of thinking about two's complement numbers.

This article gives us the worst way: "you form a negative number from its positive by inverting the bits and adding 1". Insight into what's going on will be limited.

You could also say, "in two's complement, the most significant bit has a negative value rather than a positive value". So the bit values for a four-bit two's complement number would be -8, 4, 2, and 1. You then add those up in the normal way and you have your number: 1011 = -8+2+1 = -5.

But the reason two's complement works is that in fact all the bits have their normal positive value. Instead, the two's complement convention is that all bits which the variable is too small to express match the most significant bit, giving an infinite geometric series. For example, it's easy to verify that 1111 (with an infinite number of leading 1s) is the sum from 0 to infinity of 2^i, and that that sum evaluates to -1, which is the value of 1111 in (four-bit) two's complement. That's why you can add two's complement numbers in the normal way and get correct results.


I already knew about two's complement, but I like your explanation better than the blog post.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: