Q:

(Computer architecture: bit-level operations) A short value is stored in 16 bits. Write a program that prompts the user to enter a short integer and displays the 16 bits for the integer. Here are sample runs:

0

(Computer architecture: bit-level operations) A short value is stored in 16 bits. Write a program that prompts the user to enter a short integer and displays the 16 bits for the integer. Here are sample runs:

Output:

Enter an integer: 5
The bits are 0000000000000101

Enter an integer: -5
The bits are 1111111111111011

(Hint: You need to use the bitwise right shift operator (>>) and the bitwise AND operator (&), which are covered in Appendix G, Bitwise Operations.)

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

/*
(Computer architecture: bit-level operations) A short value is stored in 16 bits.
Write a program that prompts the user to enter a short integer and displays the 16
bits for the integer. Here are sample runs:
*/
import java.util.Scanner;

public class Exercise_05_44 {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);

		// Prompt the user to enter a short integer
		System.out.print("Enter an integer: ");
		short number = input.nextShort();

		String bits = "";	// Holds the bits

		// Get the 16 bits for the integer 
		for (int i = 0; i < 16; i++) {
			bits = (number & 1) + bits;
			number >>= 1;
		}

		// Display result
		System.out.println("The bits are " + bits);
	}
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now