How can I convert integers to binary or hexadecimal?

Showing Answers 1 - 5 of 5 Answers

Tanushri

  • Jul 19th, 2005
 

we can convert integer to binary by deviding  
integer no. by 2 & storing the no. in a variable 

  Was this answer useful?  Yes

kartik

  • Jul 21st, 2005
 

u need to specify what base ur integer is in .... an integer could be a binary no or decimal ....  
i htink its just a googly  

  Was this answer useful?  Yes

hari_it_205

  • Aug 13th, 2005
 

we can convert the gn integer no into binary and hex no by using %x for binary and %e for hexadecimal in the printf statement instead of %d

RichNistuk

  • Oct 1st, 2005
 

Here is my solution:

#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;

}

Note the while loop makes use of the fact that if you start at 1 and double the number each loop then eventually the value will return to 0. Don't do this in real code!

  Was this answer useful?  Yes

grvmab

  • Oct 3rd, 2010
 

#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,b[10],c=0;
clrscr();
printf("nEnter the num:");
scanf("%d",&n);
while(n>0)
{
b[c]=n%2;
c++;
n=n/2;
}
printf("nBinary num:");
for(i=c;i>0;i--)
{
printf("n%d",b[i]);
}
getch();
}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions