Part 2. Using only the the arithmetic operators (+, -, *, /, %, and - (2\'s comp
ID: 3766150 • Letter: P
Question
Part 2. Using only the the arithmetic operators (+, -, *, /, %, and - (2's complement/unary negation)), implement a Java function that also swaps the byte order of an integer (ifs are OK too). Note that it is actually much more difficult to do this using only the arithmetic operators! Hint: First implement it correctly for positive i, and only then begin working on the version that also handles negative i. A template for this Java function follows: static int swap2 ( int i ) { . . . }
Please read the question before answering I have to use / or * nothing else
Explanation / Answer
Complete Program:
// File: ByteSwapTest.java
import java.util.*;
public class ByteSwapTest
{
public static int swap2(int i)
{
int bit1 = (i >> 0) & 0xFF;
int bit2 = (i >> 8) & 0xFF;
int bit3 = (i >> 16) & 0xFF;
int bit4 = (i >> 24) & 0xFF;
return bit1 << 24 | bit2 << 16 | bit3 << 8 | bit4 << 0;
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter an interger: ");
int i = input.nextInt();
System.out.println("swap2(i) = " + swap2(i));
}
}