r/AskProgramming • • Apr 13 '25

What was a topic in CS/Programming that when you learned about, made you go "Damn, this is so clever!"?

227 Upvotes

274 comments sorted by

View all comments

61

u/tubameister Apr 13 '25

How the 2’s complement representation of negative binary numbers facilitates binary arithmetic. (Beginning C++17, Ivor Horton)

0

u/[deleted] Apr 13 '25

[deleted]

3

u/zutnoq Apr 14 '25

It's more that they don't need to.

6

u/suvalas Apr 14 '25

Pretty simple when you realise how it works. Try it in base 10 - just subtract each digit from 9 then add 1.

6

u/bestjakeisbest Apr 14 '25

here is one for you 2s complement math is a specific case of complements math, and the whole idea is extendable to any base.

in 10s complement your negate operation is mapped as such:

inout
09
18
27
36
45
54
63
72
81
90

and numbers with a leading 5,6,7,8,9 are negative and numbers with a leading 0,1,2,3,4 are positive say we had the expression

5 - 8 we need to add a digit to hold the sign

05-08 next we need to negate the 08 to get the "9s complement"

05+91 now we need to add 1 to get the "10s complement"

05 + 91 + 1 now we just solve it like a normal addition problem

97 now we know that since it is a leading 9 we know this number is negative, so lets figure out its magnitude first lets negate

02 now lets add one

02 + 1

3

so now we know that 5-8 is negative 3

the reason why this works is because what complements math does is instead of doing negative numbers, we are simply mapping negative numbers in a range of half the max value to the next digit, bit, etc its like if you cut up the number line between -49 and 50 and then wrapped them around into a ring and you should be able to see -1 gets mapped to 99 -2 gets mapped to 98 and so on until -50 where in this example with 2 digits it underflows to positive 50