简体   繁体   English

我从十进制转换为二进制不能处理负数

[英]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. 我的代码是从main的for循环中调用的,该循环从-8到+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 这是main中的for循环,它调用上述方法

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

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. 您应考虑到负数将使用其2的补数表示。

Also, the method does not return a char array anymore, since it was not being used at all. 同样,该方法不再返回char数组,因为根本没有使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM