In: Computer Science
Java program - you are not allowed to use arithmetic operations such as division (/), multiplication, or modulo (%) to extract the bits. In this exercise use only logic bit-wise operations. Write a program that prompts the user to enter a positive integer n (0 up to 232 -1). You must write a function that takes as input n and returns a string s representing the number n in binary. For this assignment, you CANNOT use the arithmetic division by 2 or the modulo operation to convert the number to binary. Your main program must print out s. Example: If the user enters the number 66, your program must print out 1000010. Hints for Programming Exercise 3: Hint 1: The number n is already in binary inside the memory. All you need is to “extract” or “read” the bits CPSC 3303 Programming Project 1 individually. Read the next hints to know how. Hint 2: Consider the number n=66. In the memory, 66 is 0000000001000010. I can isolate the least significant bit (red rightmost bit) by using the logic operation AND (&). Compute n & 1 = 66 & 1. Try the operation x & 1 with x taking different values to find out the effect: the operation “& 1” returns the value of the least significant bit! Hint 3: Say, for example, you read the rightmost bit with the operation “ & 1”. How should you read the bit that is to the left of the least significant bit (i.e., the blue bit to the left of the red bit)? The hint is to push all the bits to the right after I extracted the rightmost bit. To push to the right, you can shift right (>>) the number n to the right. n >> 1 = 66 >> 1 = 0000000000100001: all bits are pushed to the right. Now, that bit became the rightmost bit. . . And you know how to read the rightmost bit.
import java.util.Scanner;
public class DecimalToBinary
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter a positive integer: ");
int n = scan.nextInt();
for (int i = 31; i >= 0; i--)
{
if ( ((1 << i) & n) != 0)
System.out.print(1);
else
System.out.print(0);
}
}
}
****This is what I have written so far, but the output below has way too many leading zeros. What do I need to do to fix this? ****
Enter a positive integer:
66
00000000000000000000000001000010
package tushar1;
import java.util.Scanner;
public class DecimalToBinary
{
public static void main(String[]args)
{
Scanner scan = new
Scanner(System.in);
System.out.println("Enter a
positive integer: ");
int n = scan.nextInt();
String s="";
while(n>0)
{
if((n&1)==1)
s="1"+s;
else
s="0"+s;
n=n>>1;
}
System.out.println(s);
}
}