my code:
public class d2b { private int decnum, modnum, quotnum, count = 0, tot, binarray[] = new int[16], convnum, alter = 1; d2b(int decpass){ //decpass is passed from any other class or main as an integer. decnum = decpass; } public void convert(){ while(decnum > 1){ modnum = decnum % 2; quotnum = decnum / 2; decnum = quotnum; binarray[count] = modnum; count++; } binarray[count] = decnum; while(count >= 0){ if(alter == 1){ convnum = 1; alter++; } else{ if(binarray[count] == 1){ convnum = (convnum * 10) + 1; } else{ convnum = convnum * 10; } } count--; } System.out.printf("%d", convnum); } }
What it tries to do:
I wrote this program as my assignment. I came up with the logic(finally *phew*) for a program to convert decimal to binary and store it as an integer. I tried the algorithm without the arrays but couldn't solve it at all(maybe i am dumb ), so i used arrays and successfully was able to complete this task within minutes. however, now i can only convert the values upto certain numbers....ex, if i pass 999, it will convert the value as 1111100111 but if i pass 9999 it will show -468765865. i have a hunch, that, its because i have to do it as 'long int' data type, am i right? if not where am i going wrong? also when i derived the algo for it i saw that it wouldn't need more than 15 array size or am i wrong there too?
Please any input would be helpful. Thank you.