Write a program in java which takes as input an integer posi

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.

Use a twos-complement representation for negative numbers

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’

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

You may not use any built in conversion operators or print operators that can do the conversion automatically (i.e. NO printf(‘%x’,number)).

Solution

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

package javaapplication3;

import com.sun.jmx.snmp.BerDecoder;
import static java.lang.Math.pow;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
*
* @author Namburi Ramesh
*/
public class Project4 {

/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
System.out.println(getbinary(-2));
}

public static String getbinary(int a){
String result=\"\";
int bin[]=new int[32];
char hex[]=new char[8];
char digits[]={\'0\',\'1\',\'2\',\'3\',\'4\',\'5\',\'6\',\'7\',\'8\',\'9\',\'A\',\'B\',\'C\',\'D\',\'E\',\'F\'};
//calculating binary form
if(a>=0){
for(int i=31;i>=0;i--){
bin[i]=a%2;
a=a/2;
}
}else{
a=a*-1;
for(int i=31;i>=0;i--){
bin[i]=a%2;
a=a/2;
}
//calculating twos complement if input is negative
bin[0]=1;
for(int i=31;i>0;i--){
if(bin[i]==1){
bin[i]=0;
}else{
bin[i]=1;
}
  
}
int carry=1;
for(int i=31;i>0;i--){
if(bin[i]==1 && carry ==1 ){
bin[i]=0;
carry=1;
}else{
bin[i]=bin[i]+carry;
carry=0;
}
  
}

}

//calculating hexadecimal form
int iterator=31;
for(int i=7;i>=0;i--){
int sum=0;

for(int j=0;j<4;j++){
sum=(int) (sum+(bin[iterator]*(pow(2,j))));   
iterator--;
}
hex[i]=digits[sum];
}
//preparing string to return
result=result+\"Binary String -- \";
for(int i=0;i<32;i++){
result= result+bin[i];
}
result= result+\" Hexadecimal Representation -- \";
for(int i=0;i<8;i++){
result= result+hex[i];
}
return result;

}
}
  

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 hexade
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 hexade

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site