This will print out the binary in reverse order, but when I try to turn reverse it to the correct order, it doesn't work. I've been able to make this work in previous programs before, but using the same concepts won't work :/
/*
Given a string of no more than 50 characters (a character array), you need to write a
function that converts character by character the string into its binary equivalent
and prints out the bits of each character.
*/
#include <iostream>
#include <string>
usingnamespace std;
//prints the binary represntation of the string
void bin(char *str, int length);
void rev(int *binArr);
int main()
{
cout << "Enter a string: " << endl;
char str[256];
gets_s(str);
int length = strlen(str);
bin(str, length);
system("pause");
return 0;
}
void bin(char *str, int length)
{
unsignedint dec10; //decimal base 10
int *dec = newint[length];
//converts char to int
for (int d = 0; d < length; d++)
{
dec10 = static_cast<int>(str[d]);
dec[d] = dec10;
}
int bin2; //binary of base 2
int binary; //binary number
int c = 0;
int binArr[8];
//converts int to binary
for (int b = 0; b < length; b++)
{
bin2 = dec[b];
//comes up with binary reversed
for (int p = 0; p < 8; p++)
{
//if the number is even
if ((bin2 % 2) == 0)
binary = 0;
//if the number is odd
else
binary = 1;
binArr[b] = binary;
bin2 /= 2; //divide by 2
}
/*This is where I try to reverse the output. Have tried it in different locations in the function, wont work.
*/
for (int rev = 7; rev >= 0; rev--)
{
cout << binArr[rev];
}
cout << " ";
}
}
Still doesnt work. I think it has something to do with my placement. Because if I dont reverse it, it will print the binary numbers, but just in reverse order...