reverse an array

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 :/

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
  /*
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>
using namespace 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)
{
	unsigned int dec10;			//decimal base 10
	int *dec = new int[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 << " ";
	}	
}
You can reverse an array like this.
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
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;

int main()
{

	cout << "Enter a 30 or less charadcters: " << flush;
	char arr[31] = { ' ' };
	cin.getline(arr, 31);


	cout << "Your string reversed is: " << flush;
	reverse(&arr[0], &arr[strlen(arr)]);
	
	int i = 0;

	while (arr[i] != '\0')
	{
		cout << arr[i];
		i++;
	}

	cin.ignore();
	return 0;
}


Last edited on
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...
In line 57: binArr[b] = binary; the b should be a p.
Last edited on

In line 57: binArr[b] = binary; the b should be a p.


That's awesome thanks!! Rookie mistake. :)
Topic archived. No new replies allowed.