Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Below is my algorithm to convert a decimal number into a binary number. It seems

ID: 3563962 • Letter: B

Question

Below is my algorithm to convert a decimal number into a binary number. It seems to work fine for anything that is 5 bits or more. For example, when i input 23, it prints [1, 0, 1, 1, 1] which i believe is correct. However, anything 4 bits or below does not come out correctly. for example, 3 prints as [1, 0] and 15 is [1, 0, 1, 1].

What did i do wrong in my algorithm?

And how can i have it print 10111 instead of [1, 0, 1, 1, 1]??

private static void unsignedDec(){
Scanner scan = new Scanner(System.in);
System.out.print(" Enter number (Integers only): ");
int dec = scan.nextInt();
int bits = (int)(Math.log(dec)/Math.log(2)) + 1;
int dec1 = dec;
int temp;
int[] binary = new int[bits];
for (int i = bits - 1; i > 1; i--){
temp = dec1;
dec1 = dec1/2;
binary[i] = temp - (dec1*2);
}
temp = 2^(bits-1);
if(dec >= temp){
binary[0] = 1;
}
System.out.println(Arrays.toString(binary));
}

Explanation / Answer

You have done few errors in your code. So I will mention one after the other.

I have edited your code to work properly. Edited statements were highlighted and reasoning is given in comments in the code.

public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print(" Enter number (Integers only): ");
int dec = scan.nextInt();
int bits;
if(dec!=0) bits = (int)(Math.log(dec)/Math.log(2)) + 1; // Since log(0) is not defined.
else bits=1; // 0 has only one bit.

int dec1 = dec;
int temp;
int[] binary = new int[bits];
for (int i = bits - 1; i >= 1; i--){   // For 2 bit numbers, least significant bit has to be filled here.

temp = dec1;
dec1 = dec1/2;
binary[i] = temp - (dec1*2);
}     // (^) operator has special meaning in java i.e. It represents bitwise XOR.
temp = (int)Math.pow(2,bits-1); // So for getting 2^(bits-1) we need to write in they way shown.
if(dec >= temp){
binary[0] = 1;
}
System.out.println(Arrays.toString(binary));

for(int i=0;i<binary.length;i++) System.out.print(binary[i]); System.out.println("");

   // This line is used for printing, without commas.

}

// Other than these few errors , your code is right.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote