Java Exercises: Convert a binary number to hexadecimal number
Java Basic: Exercise-23 with Solution
Write a Java program to convert a binary number to hexadecimal number.
Binary number: A binary number is a number expressed in the base-2 numeral system or binary numeral system. This system uses only two symbols: typically 0(zero) and 1(one).
Hexadecimal number: This is a positional numeral system with a radix, or base, of 16. Hexadecimal uses sixteen distinct symbols, most often the symbols 0-9 to represent values zero to nine, and A, B, C, D, E, F (or alternatively a, b, c, d, e, f) to represent values ten to fifteen.
Test Data:
Input a binary number: 1101
Pictorial Presentation: Binary to Hexadecimal number
Sample Solution:
Java Code:
import java.util.Scanner;
public class Exercise23 {
public static void main(String[] args)
{
int[] hex = new int[1000];
int i = 1, j = 0, rem, dec = 0, bin;
Scanner in = new Scanner(System.in);
System.out.print("Input a Binary Number: ");
bin = in.nextInt();
while (bin > 0) {
rem = bin % 2;
dec = dec + rem * i;
i = i * 2;
bin = bin / 10;
}
i = 0;
while (dec != 0) {
hex[i] = dec % 16;
dec = dec / 16;
i++;
}
System.out.print("HexaDecimal value: ");
for (j = i - 1; j >= 0; j--)
{
if (hex[j] > 9)
{
System.out.print((char)(hex[j] + 55)+"\n");
} else
{
System.out.print(hex[j]+"\n");
}
}
}
}
Sample Output:
Input a Binary Number: 1101 HexaDecimal value: D
Flowchart:
Java Code Editor:
Contribute your code and comments through Disqus.
Previous: Write a Java program to convert a binary number to decimal number.
Next: Write a Java program to convert a binary number to a Octal number.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework