#include <cstdio> void prnBits(unsigned int val){ unsigned int m = 1 << sizeof(val)*8-1; while(m){ printf("%d", (val & m)&&1); m = m >> 1; } } //set the bit at bitNo to value void setBit(unsigned int& V, int bitNo, bool value){ unsigned int mask; if (bitNo >= 1 && bitNo <= (sizeof(V) * 8)){ mask = 1 << (bitNo - 1); V = (value)? (V | mask): (V & ~(mask)); } } // from bit number "bitNo" in mask copies NoOfBits bits into V void copyBits(unsigned int& V, int bitNo, int NoOfBits, unsigned int mask){ unsigned int m; int i; if (bitNo >= 1 && NoOfBits >= 1){ m = 1 << (bitNo - 1); for (i = bitNo; i < bitNo + NoOfBits && i <= (sizeof(V) * 8); i++){ // (mask & m) >> (i - 1) give mask's bitNo-th digit setBit(V, i, (mask & m)>>(i-1)); m= m << 1; } } } int main(){ unsigned int A = 0x5C; unsigned int M = 0x85025512; printf("A (Before copy): %02X\n", A); prnBits(A); putchar('\n'); printf("M: %02X\n", M); prnBits(M); putchar('\n'); copyBits(A,5,8,M); printf("A (After copy): %02X\n", A); prnBits(A); putchar('\n'); return 0; }
Sunday, 24 March 2013
OOP344 Week 11: Copy Bits
The following is the code for copying bits from a mask to a number:
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment