Write a program to convert a binary number to a hexadecimal number.
Example 1:
Input:101011
Output:2B
Example 2:
Input:11010
Output:1A
Approach
Java
public class BinaryToHexadecimal {public static void main(String[] args) {String binary = "11010";String hexadecimal = binaryToHexadecimall(binary);System.out.println("Hexadecimal is " + hexadecimal);}public static String binaryToHexadecimall(String binary) {String hexa = "";// check binary length divisible by 4int l = binary.length() % 4;// add remaining 0 in prefixif (l != 0) {l = 4 - l;while (l > 0) {binary = "0" + binary;l--;}}// loop run in 4-4 groupfor (int i = binary.length() - 1; i >= 0; i = i - 4) {int decimal = 0;int power = 0;for (int j = i; j > i - 4; j--) {if (binary.charAt(j) == '1') {decimal += Math.pow(2, power);}power++;}// convert decimal to hexadecimalhexa = decimalToHexadecimall(decimal) + "" + hexa;}return hexa;}public static String decimalToHexadecimall(int decimal) {String hexa = "";while (decimal > 0) {// calculate mode on base 16int mode = decimal % 16;if (mode < 10) {hexa = mode + hexa;} else {// 56+10='A', 56+11=Bhexa = (char) (56 + (mode - 1)) + "" + hexa;}decimal = decimal / 16;}return hexa;}}
C++
#include <bits/stdc++.h>using namespace std;//Function to convert binary to//hexadecimalstring binaryToHexadecimal(string s){int n=s.size();int m=n%4;if(m!=0)m=4-m;reverse(s.begin(),s.end());//make the string length factor of 4while(m--)s+='0';string ans="";reverse(s.begin(),s.end());//new length of stringn=s.size();for(int i=0;i<=n-4;i+=4){int res=0;for(int j=0;j<4;j++){if(s[i+j]=='1')res=res+pow(2,3-j);}if(res==16)ans+="10";else{m=res%16;if(res<=9)ans+=to_string(res);elseans+='A'+res%10;}}return ans;}int main(){string str="11010";string hexadecimal=binaryToHexadecimal(str);cout<<"Hexadecimal is ";cout<<hexadecimal<<"\n";return 0;}
No comments:
Post a Comment