16. What do the following two code fragments do given integers a and b? a-a+b, a
ID: 3736779 • Letter: 1
Question
16. What do the following two code fragments do given integers a and b? a-a+b, a a b, ; Just print the code you wrote with comment 1. Bit reversal. Write a function that takes an integer input, reverse its bits, and returns that integer. For example, if n 8, and the input is 13 (00001101), then its reversal is 176 (10110000). Count the number of 1 bits. Write function that takes an integer input and returns the number of 1's in its binary representation. RGBA color format Some of Java's classes (Bufferedlmage, PixelGrabber) use a special encoding called RGBA to store the color of each pixel. The format consists of four integers, representing the red, green, and blue intensities from 0 (not present) to 255 (fully used), and also the alpha transparency value from 0 (transparent) to 255 (opaque). The four 8-bit integers are compacted into a single 32-bit integer. Write a code fragment to extract the four components from the RGBA integer, and to go the other way. 2. 3.Explanation / Answer
Hi Student,
16. This program basically swaps the values of two variables.
import java.*;
public class SwapNumbers {
public static void main(String a[]){
int x = 10;
int y = 5;
// Code to swap 'x' (1010) and 'y' (0101)
x = x ^ y; // x now becomes 15 (1111)
y = x ^ y; // y becomes 10 (1010)
x = x ^ y; // x becomes 5 (0101)
System.out.println("After swap: x = "
+ x + ", y = " + y);
}
}
1. Bit Reversal
class BitReversal
{
// function to reverse bits of a number
public static int reverseBits(int n)
{
int rev = 0;
// traversing bits of 'n'
// from the right
while (n > 0)
{
// bitwise left shift
// 'rev' by 1
rev <<= 1;
// if current bit is '1'
if ((int)(n & 1) == 1)
rev ^= 1;
// bitwise right shift
//'n' by 1
n >>= 1;
}
// required number
return rev;
}
// Driver code
public static void main(String[] args)
{
int n = 8;
System.out.println(reverseBits(n));
}
}
2. Count the number of 1 bits.
// Java program to Count set
// bits in an integer
import java.io.*;
class countSetBits
{
/* Function to get no of set
bits in binary representation
of positive integer n */
static int countSetBits(int n)
{
int count = 0;
while (n > 0)
{
count += n & 1;
n >>= 1;
}
return count;
}
// driver program
public static void main(String args[])
{
int i = 9;
System.out.println(countSetBits(i));
}
}
Happy Learning :)
import java.*;
public class SwapNumbers {
public static void main(String a[]){
int x = 10;
int y = 5;
// Code to swap 'x' (1010) and 'y' (0101)
x = x ^ y; // x now becomes 15 (1111)
y = x ^ y; // y becomes 10 (1010)
x = x ^ y; // x becomes 5 (0101)
System.out.println("After swap: x = "
+ x + ", y = " + y);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.