Win a copy of Java EE 8 High Performance this week in the Java/Jakarta EE forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Binary to decimal

Ranch Hand
Posts: 486
3 bit value is---->11
fliping gives----->1111 1111 1111 1111 1111 1111 1111 1111 1100
add 1 gives----> 1111 1111 1111 1111 1111 1111 1111 1111 1101(this is the result of -3 bit representation)
But when i convert the previous bit representation back to decimal as 1*2^0+0*2^1+1*2^2--->-5 (why it is not giving -3 value)
Then how come the bit representation is the result of -3.
Am i making any sense here?

Ranch Hand
Posts: 2410
To convert it back to decimal, do the process again.

Flip the bits and add 1.

Ranch Hand
Posts: 401
Hello.

The way you're looking at it is not correct. If you look at it that way, that value wouldn't even be -5, because you have to count all 1's that correspond to the left most bits. Then, it would be:

1*2^0 + 0*2^1 + 1*2^2 + 1*2^3 + *2^4 + *2^5 + *2^6 ... (a very large number)

Here's how you should evaluate the number (suppose 8 bits in the representation):

0000 0011 (base 2) = 3 (base 10)

We want -3, so we compute the two's complemente (as you suggested). We invert the bits:

1111 1100

1111 1101

The representation above is -3 (in two's complement). How do we know that? We first note that the most significant bit is 1.

1....... (ok, we have a negative number)

Since we know we have a negative number, its value is the corresponding positive value. So, we invert the bits back:

0000 0010

0000 0011

Now, we have 3 and we know that the negative number is -3.

To look at in a way closer to what you want, you would have to do the math computing the most significant bit as a negative value. For example, suppose that we our two's complement of three:

1111 1101

We can use the power of twos in the following way:

1111 1101 = -1*2^7 + 1*2^6 + 1*2^5 + 1*2^4 + 1*2^3 + 1*2^2 + 0*2^1 + 1*2^0
1111 1101 = -128 + 64 + 32 + 16 + 8 + 4 + 0 + 1
1111 1101 = -3

Is that clear now?

 Ruth Stout was famous for gardening naked. Just like this tiny ad: The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS