Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a decimal base (10) to a negabinary base (-2)?

I want to write a program to convert from decimal to negabinary.

I cannot figure out how to convert from decimal to negabinary.

I have no idea about how to find the rule and how it works.

Example: 7(base10)-->11011(base-2)

I just know it is 7 = (-2)^0*1 + (-2)^1*1 + (-2)^2*0 + (-2)^3*1 + (-2)^4*1.

like image 631
Jason Avatar asked Feb 17 '12 15:02

Jason


People also ask

How do you convert base 10 numbers to base 2?

Steps To Convert From Base 10 to Base 2-Divide the given number (in base 10) with 2 until the result finally left is less than 2. Traverse the remainders from bottom to top to get the required number in base 2.

How do you convert a base 10 number to a base?

To convert any number in (our base) Base 10 to any other base, we must use basic division with remainders. Do not divide using decimals; the algorithm will not work. Keep dividing by 5, until your quotient is zero. Now write your remainders backwards!


2 Answers

The algorithm is described in http://en.wikipedia.org/wiki/Negative_base#Calculation. Basically, you just pick the remainder as the positive base case and make sure the remainder is nonnegative and minimal.

 7 = -3*-2 + 1  (least significant digit)
-3 =  2*-2 + 1
 2 = -1*-2 + 0
-1 =  1*-2 + 1
 1 =  0*-2 + 1  (most significant digit)
like image 124
kennytm Avatar answered Sep 30 '22 09:09

kennytm


def neg2dec(arr):
    n = 0
    for i, num in enumerate(arr[::-1]):
        n+= ((-2)**i)*num
    return n

def dec2neg(num):
    if num == 0:
        digits = ['0']
    else:
        digits = []
        while num != 0:
            num, remainder = divmod(num, -2)
            if remainder < 0:
                num, remainder = num + 1, remainder + 2
            digits.append(str(remainder))
    return ''.join(digits[::-1])
like image 24
Birender Singh Avatar answered Sep 30 '22 09:09

Birender Singh