understanding someone else code.

Thx for reading, I found this code the other day and wanted to understand it so saved it, complied it, found it seemed extreemly powerful for so small a program. Then I forgot about it, went home, slept a few days, and came back to look at it today.

For the life of me I can't figure out what it's doing.
I added all the lines that say
// test and the comments.

The questions I have are largely in the comments. I understand the for loop on line 19 but the one on line 33 i have not seen before. I need help on line 24 and 29 because they are not giving values that I would expect. I'm sure it's something simple I have not learned yet.

Thx 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
// convert single char to bin 1's and 0's
// ascii chart http://www.nthelp.com/ascii.htm

#include <iostream>
#include <cmath>
 
using namespace std;
 
int main()
{
    char character;
    int i;
    int m[8];
  
    cout <<"Please enter a character: ";
    cin >> character;
    cout <<"You entered: "<<character <<endl;
 
    for(i=0;i<8;i++)
    {
    	// I see this line outputs the binary numbers in reverse order
    	// but I can't figure out the logic.
        m[i] = character%2;
        cout << "character%2 = " << character%2;			// test
		cout << "\tcharacter = " << character;				// test
		// I can not figure out this at all, 1/2 hex a should be 30
		// The only thing I can think of is half the decimal digit 0, which is 48.
        character = character/2;
        cout << "\tcharacter/2 = " << character/2 << endl;  // test
    }
 
    int top, bottom;
    for(bottom=0,top =7; bottom<8; bottom++,top--)
    {
        cout<<m[top];
    }
 
    return 0;
}

/*  OUTPUT

Please enter a character: a
You entered: a
character%2 = 1 character = a   character/2 = 24
character%2 = 0 character = 0   character/2 = 12
character%2 = 0 character = ?   character/2 = 6
character%2 = 0 character = ?   character/2 = 3
character%2 = 0 character = ?   character/2 = 1
character%2 = 1 character = ?   character/2 = 0
character%2 = 1 character = ?   character/2 = 0
character%2 = 0 character =     character/2 = 0
01100001

*/
character%2 will get the least significant bit of character. Dividing by two will shift the binary representation one place to the right. Then the loop repeats, getting the new least significant bit, over and over.

Does that help?
When you mod (%) the least significant digit in a number in binary format with 2 you get the remainder which is always 0 or 1, When you divide that number by 2 you effectively lop off the least significant digit. So now you have a 7 digit binary number where in the loop you repeat the mod by 2 and divide by 2, and so on. (as Zhuge has said)
Topic archived. No new replies allowed.