Help with Error - Binary to Character Converter
Hi. I wrote a binary to character converter program but I have a problem - after I type in the binary (e.g. 01000001) the program stops with an error. I ran it in win XP and linux but both give error.
The errors:
XP:
F:\>bin2char-0.1
Enter string to convert : 01000001
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
and linux:
[dvldrmmr@myhost /]# ./bin2char-0.1
Enter string to convert : 01000001
Aborted
Any ideas why I get an error? I wrote an *almost* identical app in VB (basic vs. c++) and it worked fine.
My code (I know its not too pretty :D ):
Code:
/***********************************************************/
/* bin2char-0.1.cpp - Binary to Character Converter v. 0.1 */
/***********************************************************/
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{ string bin_stream, char_stream;
int ascii_num, char_start;
int count = 0;
char ch;
cout << "Enter string to convert : ";
cin >> bin_stream;
if(bin_stream.length() % 8 != 0){
cout << "Incorrect input string!!\n";
return 0; }
for(int i = bin_stream.length(); i > 0; i - 8){
for(int j = 0; j <= 7; j++){
char_start = count * j + 1;
ch = bin_stream.at(char_start + j);
if(ch == '1'){ ascii_num += (int)(pow((double)2,j)); }
}
count++;
char_stream += (char)ascii_num;
}
cout << "Converted string:\n" << char_stream << endl;
return 0;
}
Is it my code?
Any help appreciated. Thanks.
...And now for the easy way!
FYI - There are two secret functions in <cstdlib> that will convert from any* base: strtoul() = String To Unsigned Long, and strtol() = String to Long.
I call them secret functions, because I ran-across strtoul() in a program, but couldn't find it in any of my C++ books. So I started searching for a complete C++ reference book. I've never found a complete book, but I did find Dinkumware.com, which does seem to be a complete online reference. :)
There is no complimentary standard C++ function to output/display a number in any base. If you have a Microsoft compiler, _itoa() = Integer To ASCII, will do it. For binary display/output <bitset> is standard.
*Any base between 2 and 36 (base-2 to base-z.) [Corrected. Thanks, Dave.]