TechArena Community Program to Convert Hexadecimal No into Binary No in C language

#1
06-03-2009
 Member Join Date: Jan 2009 Posts: 85
Program to Convert Hexadecimal No into Binary No in C language

hi there

I need a small help from you people as to convert Hexadecimal number to Binary number in C language.

Please provide some views as i am not so good programmer in c language
#2
06-03-2009
 Member Join Date: Apr 2008 Posts: 1,948
Re: Program to Convert Hexadecimal No into Binary No in C language

To convert hexadecimal to binary, at each hexadecimal digit we associate the 4 bits binary number using the following table:
0 0000
1 0001
2 0010
3 0011
4 0100
5 0101
6 0110
7 0111
8 1000
9 1001
A 1010
B 1011
C 1100
D 1101
E 1110
F 1111

.
For example, FCB1=1111110010110001:
#3
06-03-2009
 Member Join Date: May 2008 Posts: 2,008
Re: Program to Convert Hexadecimal No into Binary No in C language

#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std;
string toBinary(unsigned int num)
{
stringstream s;
for(int i=0; i<sizeof(int)*8; ++i){
s << (num&0x0001) ;
num >>=1;
}
return s.str();
}
void outLine(unsigned int num)
{
cout << setw(10)<< dec << num;
cout << " bin: " << toBinary(num);
cout << " hex:" << hex << setw(10) << num << endl;
}
int main()
{
unsigned int num=0;
outLine(num);
num=1;
while(num>0) {
outLine(num);
num *=2;
}
outLine(UINT_MAX);
cout << endl;
return 0;
}
#4
06-03-2009
 Member Join Date: Apr 2008 Posts: 2,001
Re: Program to Convert Hexadecimal No into Binary No in C language

Dim Binstr As String
Hexstr = Hex\$(number)
For LV = 1 To Len(HexStr)
Select Case Mid\$(Hexstr, LV, 1)
Case "0"
BinStr = BinStr & "0000"
Case "1"
BinStr = BinStr & "0001"
Case "2"
'and so on.
Case "15"
BinStr = BinStr & "1111"
End Select
Next
#5
06-03-2009
 Member Join Date: May 2008 Posts: 2,293
Re: Program to Convert Hexadecimal No into Binary No in C language

import java.io.*;
import java.lang.*;

public class BinaryToHexa{
public static void main(String[] args)throws IOException{
System.out.println("Enter the Binary number:");
long num = Long.parseLong(hex);
long rem;
while(num > 0){
rem = num % 10;
num = num / 10;
if(rem != 0 && rem != 1){
System.out.println("This is not a binary number.");
System.exit(0);
}
}
int i= Integer.parseInt(hex,2);
String hexString = Integer.toHexString(i);
System.out.println("Hexa decimal: " + hexString);
}
}