Converting String to Binary
Sep 26, 2011 at 12:06am UTC
I'm attempting to read in a file and convert it into its binary representation. The program returns the correct representation for all of the characters that have been sent to it, but unfortunately I get the same 9 character junk after each output. Here's the code that I'm working with, if anyone can see what my issue is please let me know. Thank you in advance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
// decompress.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
void charToBinary(const char * ch)
{
int ascii;
int length = strlen(ch);
cout << " " ;
for (int i = 0; i < length; i++){
ascii = ch[i];
cout << "Ascii for " << ch[i] << " " << ascii << " " ;
char * binary_reverse = new char [9];
char * binary = new char [9];
int j = 0;
while (ascii != 1){
if (ascii % 2 == 0){
binary_reverse[j] = '0' ;
}
else if (ascii % 2 == 1){
binary_reverse[j] = '1' ;
}
ascii /= 2;
j++;
}
if (ascii == 1){
binary_reverse[j] = '1' ;
j++;
}
if (j < 8){
for (; j < 8; j++){
binary_reverse[j] = '0' ;
}
}
for (int z = 0; z < 8; z++){
binary[z] = binary_reverse[7 - z];
}
cout << "Binary for " << ch[i] << " " << binary << endl;
delete [] binary_reverse;
delete [] binary;
}
cout << endl;
}
int readem(string path){
ifstream infile(path);
string line;
const char * ch;
if (infile.is_open())
{
cout<<"file " <<path<<" is open." <<endl;
while (infile.good())
{
getline(infile, line);
ch = line.c_str();
charToBinary(ch);
}
return 0;
}
else
return -1;
}
int main(int argc, char * argv[])
{
readem(argv[1]);
return 0;
}
Sep 26, 2011 at 12:22am UTC
to be honest I didn't read all of your code but the following function will convert a char to binary
1 2 3 4 5 6 7 8 9 10 11 12 13
void converttobinary(char c)
{
int bits[8], i;
for (i = 0; i < 8; i++)
bits[i] = ((1<<i) & c) != 0 ? 1:0;
for (i = 7; i >= 0; i--)
std::cout << bits[i];
std::cin.get();
return 0;
}
I imagine if you just went through your file reading in char by char and just converting one char at a time the problem could be eliminated.
Last edited on Sep 26, 2011 at 12:22am UTC
Topic archived. No new replies allowed.