// this file contains some functions that do bitwise operation // X. Meng 9/91 // bitwise operators: // << shift left // >> shift right // & bitwise AND // | bitwise OR // ^ bitwise XOR (exclusive OR) // ~ complement (invert all bits) #include #include #define BITSinCHAR 8 #define LOWPOS 1 // the lowest position can be 1 or 0 unsigned short setbit(unsigned short m, int pos, int value); unsigned short getbit(unsigned short m, int pos); main() { unsigned short x; int position, value; // which bit? what value (0,1)? cout << "input value of x \n"; cin >> x; cout << "which position \n"; cin >> position; cout << "what value \n"; cin >> value; x = setbit(x, position, value); cout << "value of x now is " << x << '\n'; cout << "input value of x \n"; cin >> x; cout << "which position \n"; cin >> position; x = getbit(x, position); cout << "value of bit at position " << position << " is " << x << '\n'; cout << "value of negation " << ~x << endl; } unsigned short setbit(unsigned short m, int pos, int value) // set 'pos' bit of 'm' to be 'value', either 0 or 1 // 'pos' being from right to left, i.e. 87654321 { unsigned short mask; if (pos >= (sizeof(unsigned short)*BITSinCHAR)+LOWPOS || pos < LOWPOS) { cerr << " position out of range \n"; exit(1); } if (value == 1) // set mask to be, for example 000000100000 { mask = 1; mask = mask << (pos - LOWPOS); return (m | mask); } if (value == 0) // set mask to be, for example 111111011111 { mask = 1; mask = ~(mask << pos+1-LOWPOS); return (m & mask); } else return 0; } unsigned short getbit(unsigned short m, int pos) // getbit returns the value of bit 'pos' in number 'm' { unsigned short mask; mask = 0; // all 0's mask = setbit(mask,pos,1); // set bit 'pos' to be one m = m & mask; // only bit 'pos' keeps original value m = m >> (pos-LOWPOS); return (m); }