Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

trouble working with binary numbers

Status
Not open for further replies.

dendog

Programmer
Jun 28, 2001
53
US
hey all;
I have a few questions about how to work with binary numbers in C++:
1. How do you read in a binary number
2. How do you print out a binary number
3. how do you store a binary number
4. how do u convert a number from its decimal form to its binary equivalent
5. how do you convert a binary number to its decimal equvalent

Are there special function and classes to do these things??

Thank you very much for all your help in advance
 
As per my knowlege there are no special functions for it. As u know, any decimal number are stored in binary format in the memory. You can display them in Hexadecimal format using %x or %X in the printf statement.

Hope this helps

raochetan
 
1. How do you read in a binary number

char binary_number[32];
char* endPtr;
int binary_value;
cin>>binary_number;
binary_value = strtol(binary_number,endPtr,2);

2. How do you print out a binary number

for(int i = 0, j = 31;i<32;i++,j--)
{
binary_number[j] = (binary_value & (1<<i) ? '1':'0');
}
cout<<binary_number;

or


for(int i = 0, j = 31;i<32;i++,j--)
{
int bit = (binary_value & 1<<j ? 1:0);
cout<<bit;
}
cout<<endl;



3. how do you store a binary number

see above... a binary number can be put into a regular int once the conversion is done

4. how do u convert a number from its decimal form to its binary equivalent

That is a more interesting question. I have not done this but it deals with a mantisa and a bunch of other different formatting issues. Search this forum and other forums related to C/C++. I believe it was discussed already.

5. how do you convert a binary number to its decimal equvalent

see above

Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top