Skip to content

Added Binary To Hexadecimal #314

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 15, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions Conversions/BinaryToHexadecimal.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import java.util.*;
/**
* Converts any Binary Number to a Hexadecimal Number
*
* @author Nishita Aggarwal
*
*/
public class BinaryToHexadecimal {

/**
* This method converts a binary number to
* a hexadecimal number.
*
* @param binary The binary number
* @return The hexadecimal number
*/
static String binToHex(int binary)
{
//hm to store hexadecimal codes for binary numbers within the range: 0000 to 1111 i.e. for decimal numbers 0 to 15
HashMap<Integer,String> hm=new HashMap<>();
//String to store hexadecimal code
String hex="";
int i;
for(i=0 ; i<10 ; i++)
{
hm.put(i, String.valueOf(i));
}
for(i=10 ; i<16 ; i++) hm.put(i,String.valueOf((char)('A'+i-10)));
int currbit;
while(binary != 0)
{
int code4 = 0; //to store decimal equivalent of number formed by 4 decimal digits
for(i=0 ; i<4 ; i++)
{
currbit = binary % 10;
binary = binary / 10;
code4 += currbit * Math.pow(2, i);
}
hex= hm.get(code4) + hex;
}
return hex;
}

/**
* Main method
*
* @param args Command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter binary number:");
int binary = sc.nextInt();
String hex = binToHex(binary);
System.out.println("Hexadecimal Code:" + hex);
sc.close();
}
}