theAnon
theAnon

Reputation: 77

My conversion from decimal to binary can't deal with negative numbers

I am converting decimal to binary and my code works on positive numbers but it crashes when I try to convert negative numbers. When it crashes I get the error

Exception in thread "main" java.lang.StackOverflowError

My code is being called from a for loop in main that runs from -8 to +7. This is the code for the conversion

public char[] decimalToBinary(int value) 
{
    int remainder;
    char[] result = new char[10];
    if (value <= 0)
    {

        return result; 
    }

    remainder = value %2; 
    decimalToBinary(value >> 1);
    System.out.print(remainder);
    return result;
}

This is the for loop in main that calls the above method

   int min = -8;
   int max = +7;
   for (int i = min; i <= max; ++i) 
   {
        char[] binaryStr = s.decimalToBinary(i);
   }

Upvotes: 0

Views: 164

Answers (1)

thyago stall
thyago stall

Reputation: 1704

The example below is a working code based on your logic:

public static void decimalToBinary(int value) {
    int remainder;

    if (value == 0) {
        return;
    }

    remainder = value % 2;
    decimalToBinary(value >>> 1);
    System.out.print(remainder);
}

You should take into account that the negative numbers will be represented using their 2's complement values.

Also, the method does not return a char array anymore, since it was not being used at all.

Upvotes: 1

Related Questions