Sat Sep 18 2021
Binary to Hex
Java Programming3625 views
File Name: binary-to-hex.java
/* Using single Inheritance */
import java.io.*;
import java.util.Scanner;
class todecimal {
/* Global variables */
int decimal;
todecimal(int binary) {
int reminder, i = 1;
while(binary != 0) {
reminder = binary % 10;
decimal += reminder * i;
i *= 2;
binary /= 10;
}
System.out.println("Decimal: "+decimal);
}
}
/* Inherit parent class into child class using 'extends' keyword */
class tohex extends todecimal {
int i = 1, value;
String hex = "";
tohex(int binary) {
super(binary);
while(decimal != 0) {
value = decimal % 16;
switch(value) {
case 10:
hex = hex + 'A';
break;
case 11:
hex = hex + 'B';
break;
case 12:
hex = hex + 'C';
break;
case 13:
hex = hex + 'D';
break;
case 14:
hex = hex + 'E';
break;
case 15:
hex = hex + 'F';
break;
default:
hex = value + hex;
break;
}
decimal /= 16;
}
System.out.println("Hex: "+hex);
}
}
class converter {
public static void main(String args[ ]) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a Binary Number");
tohex hex = new tohex(Integer.parseInt(input.nextLine()));
}
}
/* Output */
Please enter a Binary Number
1111
Decimal: 15
Hex: F
Reference:
Author:Geekboots