tags:

views:

402

answers:

3

For an example, assume an initial value of:

0100 0011

What is this in hex and what is it in decimal if using two's complement?

Similarly, what is it in hex and decimal if using one's complement?

More generally, how do you work out the hex and decimal values of both forms of binary representation?

+1  A: 

Hex is easy. Simply separate into 4 bit groups and convert each group to decimal. Then, obviously, replace 10 with A, 11 with B, 12 with C, 13 with D, 14 with E and 15 with F. Hex representations usually don't care about one or two's complement and simply reflect the bits exactly.

As to converting into decimal: depending on being one or two's complement, work out what the sign and absolute values would be. If the first bit is 0, it's positive, if it's 1 it's negative.

Positive values require no further modification. The absolute value of a negative value depends on it being one's or two's complement. One's complement is simply the negated bits (0 becomes 1, 1 becomes 0). For two's complement subtract 1 and then negate the bits.

Then sum the values of the bits set to 1 in the absolute value. The values of each bit are successive powers of two of increasing exponent, starting with 2^0 (=1) for the rightmost bit and increasing to the left.

Here are some wikipedia references:

Martinho Fernandes
+1  A: 

In Ruby:

Convert binary to hex:

> '01000011'.to_i(2).to_s(16)
=> "13"

Convert binary to decimal:

> '01000011'.to_i(2).to_s(10)
=> "19"

If the top bit is set you need to subtract 2**(number of bits).

For one's complement, if the top bit is set you need to subtract 2**(number of bits) then add one.

Mark Byers
A: 

I don't know if i have your question right, but

01000011 in decimal is 67 01000011 in hex is 43

while 0100 in hex AND decimal is 4 and 0011 in hex AND decimal = 3

And explanation for the conversion can be found here: http://www.permadi.com/tutorial/numBinToDec/

Tim