/*********************************************************** * bitcount.c * Unit 7 lecture notes * Counts how many bits are set in a value **********************************************************/ #include #include "inputlib.h" unsigned char setBit(unsigned char val, int pos); unsigned char unsetBit(unsigned char val, int pos); int main(void) { unsigned char val = 0xee; // test value 11101110 int i, count = 0, numBits = sizeof(val) * 8; // loop through each bit and determine if it's a 1 or 0. // If it's 1, increment count. for (i = 0; i < numBits; i++) { if ((val & (1 << i)) != 0) { printf("Bit %d set!\n", i); count++; } else { printf("Bit %d is not set!\n", i); } } printf("There are %d bits set in %#x.\n", count, val); int bitToSet, bitToUnset; printf("This is the current bitset: %#x.\n", val); printf("Enter a bit you want to set: "); bitToSet = getInt(); val = setBit(val, bitToSet); printf("This is the current bitset: %#x.\n", val); printf("Enter a bit you want to unset: "); bitToUnset = getInt(); val = unsetBit(val, bitToUnset); printf("This is the current bitset: %#x.\n", val); return 0; } unsigned char setBit(unsigned char val, int pos) { if (pos >= sizeof(unsigned char) * 8 || pos < 0) { printf("Bit position is out of bounds.\n"); } return val | (1 << pos); } unsigned char unsetBit(unsigned char val, int pos) { if (pos >= sizeof(unsigned char) * 8 || pos < 0) { printf("Bit position is out of bounds.\n"); } return val & ~(1 << pos); }