two's complement

只谈情不闲聊 提交于 2019-11-29 17:09:42
0...0010 // 2
1...1101 // Flip the bits
1...1110 // Add one

It works for negative too:

1...1110 // -2
0...0001 // Flip the bits
0...0010 // Add one

For your code you might have needed to do 2's complement: i just wanted to throw this out there(a quicker way of getting a negative binary) :

2's complement is very useful for finding the value of a binary, however I thought of a much more concise way of solving such a problem(never seen anyone else publish it):

take a binary, for example: 1101 which is [assuming that space "1" is the sign] equal to -3.

using 2's complement we would do this...flip 1101 to 0010...add 0001 + 0010 ===> gives us 0011. 0011 in positive binary = 3. therefore 1101 = -3!

What I realized:

instead of all the flipping and adding, you can just do the basic method for solving for a positive binary(lets say 0101) is (23 * 0) + (22 * 1) + (21 * 0) + (20 * 1) = 5.

Do exactly the same concept with a negative!(with a small twist)

take 1101, for example:

for the first number instead of 23 * 1 = 8 , do -(23 * 1) = -8.

then continue as usual, doing -8 + (22 * 1) + (21 * 0) + (20 * 1) = -3

Hope that may help!

What am I doing wrong?

Skipping step 3 for your second example (or misunderstanding it).

1111111111111101 is ones' complement of 2 (i.e. result of step 1 and 2); you need to add 1 - not to the last bit (as in binary digit), but to the last result (as in, what you get from step 2).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!