Write a program to convert a hexadecimal number to a binary number.
Example 1:
Input:5F
Output:1011111
Example 2:
Input:4AB
Output:10010101011
Approach
Java
public class HexadecimalToBinary {public static void main(String[] args) {String hexa = "5F";int decimal = hexaToDecimal(hexa);String binary = decimalToBinary(decimal);System.out.println("Binary is " + binary);}private static int hexaToDecimal(String hexa) {int n = hexa.length();int decimal = 0;for (int i = 0; i < n; i++) {if (Character.isDigit(hexa.charAt(i))) {int num = Integer.parseInt(String.valueOf(hexa.charAt(i)));decimal += Math.pow(16, n - i - 1) * num;} else {int num = (int) hexa.charAt(i) - 55;decimal += Math.pow(16, n - i - 1) * num;}}return decimal;}public static String decimalToBinary(int decimal) {String binary = "";while (decimal > 0) {// if decimal%2==0 then append 0 else append 1if (decimal % 2 == 0) {binary = "0" + binary;} else {binary = "1" + binary;}decimal = decimal / 2;}return binary;}}
C++
#include <bits/stdc++.h>using namespace std;//function to convert from hexadecimal to//decimalint hexadecimalToDecimal(string hexadecimal){int decimal=0;int n=hexadecimal.size();for(int i=0;i<n;i++){//if hexadecimal[i]>='0'&&hexadecimal[i]<='9'if(hexadecimal[i]>='0'&&hexadecimal[i]<='9'){int num=hexadecimal[i]-'0';decimal=decimal+pow(16,n-i-1)*num;}//if hexadecimal[i]>='A'&&hexadecimal[i]<='F'else{int num=hexadecimal[i]-'A'+10;decimal=decimal+pow(16,n-1-i)*num;}}return decimal;}//function to convert from//decimal to binarystring decimalToBinary(int decimal){string binary="";while(decimal>0){if(decimal%2==0)binary='0'+binary;elsebinary='1'+binary;decimal=decimal/2;}return binary;}int main(){string hexadecimal="4AB";int decimal=hexadecimalToDecimal(hexadecimal);string binary=decimalToBinary(decimal);cout<<"Binary is ";cout<<binary<<"\n";return 0;}
No comments:
Post a Comment