// Arup Guha
// 9/27/2021
// Using some bitwise operators for CIS 3362

#include <stdio.h>

int numBitsOn(int x);
void splitIntoChunks(unsigned int x);

int main(void) {

    // Example of a bitwise XOR.
    int plain = 135;
    int key = 216;
    int cipher = plain ^ key;
    printf("%x xor %x = %x\n", plain, key, cipher);

    // Testing numbits on function.
    for (int i=0; i<100; i++)
        printf("num bits on in %x is %d\n", i, numBitsOn(i));

    // Testing splitting int into four bytes.
    unsigned int x = (65<<24) + (176<<16) + (82<<8) + 17;
    printf("The number x is %u\n", x);
    splitIntoChunks(x);

    return 0;
}

// Returns how many bits are on in x.
int numBitsOn(int x) {
    int res = 0;

    // i is the bit location we are looking at. We add 1 to res
    // if that bit is on in x.
    for (int i=0; i<32; i++)
        if ((x & (1<<i)) != 0)
            res++;

    return res;
}

// This prints out the value of each byte of x.
void splitIntoChunks(unsigned int x) {

    // 4 bytes in an unsigned int.
    for (int i=0; i<4; i++) {

        // Look at the last 8 bits only.
        int group = x & ( (1<<8) - 1);
        printf("Group %d is %x\n", i, group);

        // Right shift away those bits we just looked at.
        x = (x >> 8);
    }
}
