Please use the simplest java code possible, not much of an experienced programme
ID: 3885705 • Letter: P
Question
Please use the simplest java code possible, not much of an experienced programmer Write a program in java which takes as input an integer (positive or negative) in base 10, and returns a string representation in 32-bit of the number in hexadecimal and binary. a. Use a twos-complement representation for negative numbers b. You can create an array of symbols 0-F to make it easier to figure out each digit. char digits[]=[‘0’,’1’,’2’,’3’,’4’,’5’,’6’,’7’,’8’,’9’,’A’,’B’,’C’,’D’,’E’,’F’]; then digits[12] will return ‘C’ c. You should convert the absolute value to binary first, then take the twos complement if the value is negative, then convert the binary to hexadecimal d. You may not use any built in conversion operators or print operators that can do the conversion automatically (i.e. NO printf(‘%x’,number)). All non-decimal numbers should be assumed to be 32-bit. When inputting or outputting binary or hex, please make sure the numbers represented are full 32-bit numbers. Do not leave off the leading 0’s or 1’s. Binary: 00001111110111010101111111011101 (32 digits) Hex: 0FDD5FDD (8 digits long)
Explanation / Answer
Solution:
NumberSystemConvertor.java
import java.util.Collections;
import java.util.Scanner;
import java.util.Stack;
public class NumberSystemConvertor {
public static char compliment(char c) {
return (c == '0')? '1': '0';
}
//Print 1's and 2's complement of binary input string
public static String findOneAndTwosComplement(String binaryValue){
int sizeOfBinaryValue = binaryValue.length();
String;
char[]twosCompliment=new char[32];
// for ones complement
for (int i = 0; i < sizeOfBinaryValue; i++){
onesCompliment += compliment(binaryValue.charAt(i));
}
//for twos compliment
twosCompliment = onesCompliment.toCharArray();
for (int i = sizeOfBinaryValue - 1; i >= 0; i--){
if (onesCompliment.charAt(i) == '1'){
twosCompliment[i] = '0';
}else{
twosCompliment[i] = '1';
break;
}
}
return String.valueOf(twosCompliment);
}
public static String decinalToBinary(int decimalNumber){
// Create Stack object
Stack<Integer> stack = new Stack<Integer>();
stack.setSize(32);
while (decimalNumber != 0){
int buffer = decimalNumber % 2;
stack.push(buffer);
decimalNumber /= 2;
}
Collections.replaceAll(stack, null, new Integer(0));
String binaryRepresentation = "";
for(Integer bit : stack){
binaryRepresentation += bit.toString();
}
return binaryRepresentation;
}
public static void main(String []args){
// User input
Scanner scanner = new Scanner(System.in);
System.out.println("Enter decimal number: ");
int decimalNumber = scanner.nextInt();
String binaryRepresentationBuffer = decinalToBinary(Math.abs(decimalNumber));
if(decimalNumber < 0){
System.out.println(" Binary representation is: "+findOneAndTwosComplement(binaryRepresentationBuffer));
}else{
System.out.println(" Binary representation is:"+ binaryRepresentationBuffer);
}
}
}