# Thread: Converting string/character to binary?

1. ## Converting string/character to binary?

Hello everyone. I am a programmer in the C/C++ language and many web languages for a few years. And I am 16-years-old. I was just wanting to make a program that will convert and print a user-specified string into binary (1's and 0's). It's just something I would like to do for fun. Would I need to convert each character to binary form? If so, how?

Matt U.

2. Convert each character to it's ASCII code. That's real easy. Just cast your char to int. Then, convert that integer in base ten to a binary number.

3. ## How would I go about doing so?

Can you please tell me how I would do that. Sorry, I've just never done anything with converting to binary, etc. :P

Code:
```#include <iostream>

using namespace std;

int main()
{
/*(4 bytes of an integer)x(8 bits of a byte)*/
const int mySize = sizeof(int)*4;
cout << "Enter a number " << endl;
int number;
cin >> number;
char bin_number[mySize];
char compare=1; /* just to set a number with 00...001 */
for(int i=0;i<mySize;i++){
/* compare the last bit of the current number, to see if itīs 1*/
if( (number&compare)==compare ) bin_number[mySize-1-i]='1';
else bin_number[mySize-1-i]='0';
number>>=1; /* shift the number one bit rigth */
}
for(int i=0;i<mySize;i++){
cout << bin_number[i];
}
cout << endl;
return 0;
}```
Hope that helps!

5. Do a search of this board or the internet, and you'll find a number of ways to convert from base ten to binary. Here's what I think is the easiest way to do it and the way I was recently taught in my Intro to CS course:
http://www.mcs.drexel.edu/~introcs/F...CurrentSlide=4

6. Very easy to do using a bitset, a few lines of code is all...

Code:
```#include <bitset>
#include <iostream>
#include <string>

using namespace std;

int main()
{
string data("Hello there.");

for( string::iterator it = data.begin(); it != data.end(); ++it )
cout << bitset<8>((unsigned long)*it) << endl;

return 0;
}```
Baring any typos, this outputs:
Code:
```01001000
01100101
01101100
01101100
01101111
00100000
01110100
01101000
01100101
01110010
01100101
00101110```