PDA

Click to See Complete Forum and Search --> : How do you convert a character to its binary value?


Wynd
Mar 31st, 2001, 11:29 AM
I want to make a program that does this, but I need to know how to do this first. Also, how would you make a loop that goes through a string and converts all the characters?

parksie
Mar 31st, 2001, 12:17 PM
This to loop through each character in a string:

void main() {
string sSrc = "Hello World!";

for(int i = 0; i < sSrc.length(); i++) {
string sRes = Convert(sSrc[i]);
cout << sRes << endl;
}
}

string Convert(char cChar) {
// Do what you want to it in this function
char pcBuf[9];

for(int i = 0; i < 8; i++) {
pcBuf[i] = ((cChar >> (8-i)) & 0x1) + '0';
}

pcBuf[9] = 0;

return string(pcBuf);
}

Not totally sure on the binary conversion there (didn't have chance to test it). If the numbers are the wrong way round just change the (8 - i) in Convert.

Wynd
Apr 5th, 2001, 05:50 PM
Can you please tell me what headers I need to include? I am getting three errors that I can't seem to getr rid of, I will post them it is helps you at all.

denniswrenn
Apr 5th, 2001, 07:01 PM
#include <iostream>
#include <string>

using namespace std;