Skip to content

Commit 7926e9c

Browse files
committed
Added Binary To Hexadecimal
1 parent c07e959 commit 7926e9c

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

Conversions/BinaryToHexadecimal.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import java.util.*;
2+
/**
3+
* Converts any Binary Number to a Hexadecimal Number
4+
*
5+
* @author Nishita Aggarwal
6+
*
7+
*/
8+
public class BinaryToHexadecimal {
9+
10+
/**
11+
* This method converts a binary number to
12+
* a hexadecimal number.
13+
*
14+
* @param binary The binary number
15+
* @return The hexadecimal number
16+
*/
17+
static String binToHex(int binary)
18+
{
19+
//hm to store hexadecimal codes for binary numbers within the range: 0000 to 1111 i.e. for decimal numbers 0 to 15
20+
HashMap<Integer,String> hm=new HashMap<>();
21+
//String to store hexadecimal code
22+
String hex="";
23+
int i;
24+
for(i=0 ; i<10 ; i++)
25+
{
26+
hm.put(i, String.valueOf(i));
27+
}
28+
for(i=10 ; i<16 ; i++) hm.put(i,String.valueOf((char)('A'+i-10)));
29+
int currbit;
30+
while(binary != 0)
31+
{
32+
int code4 = 0; //to store decimal equivalent of number formed by 4 decimal digits
33+
for(i=0 ; i<4 ; i++)
34+
{
35+
currbit = binary % 10;
36+
binary = binary / 10;
37+
code4 += currbit * Math.pow(2, i);
38+
}
39+
hex= hm.get(code4) + hex;
40+
}
41+
return hex;
42+
}
43+
44+
/**
45+
* Main method
46+
*
47+
* @param args Command line arguments
48+
*/
49+
public static void main(String[] args) {
50+
Scanner sc = new Scanner(System.in);
51+
System.out.println("Enter binary number:");
52+
int binary = sc.nextInt();
53+
String hex = binToHex(binary);
54+
System.out.println("Hexadecimal Code:" + hex);
55+
sc.close();
56+
}
57+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy