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


i converting decimal binary , code works on positive numbers crashes when try convert negative numbers. when crashes error

exception in thread "main" java.lang.stackoverflowerror 

my code being called loop in main runs -8 +7. code 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 loop in main calls above method

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

the example below working code based on 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 account negative numbers represented using 2's complement values.

also, method not return char array anymore, since not being used @ all.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -