/* * Here is the code for the bit field functions as * discussed in class. */ /* * Author: Paul J. Drongowski * Address: Computer Science Department * Tufts University * Medford, MA * * Copyright (c) 2005 Paul J. Drongowski */ #include #include using namespace std ; unsigned long int mask[] = { 0x00000001UL, 0x00000003UL, 0x00000007UL, 0x0000000FUL, 0x0000001FUL, 0x0000003FUL, 0x0000007FUL, 0x000000FFUL, 0x000001FFUL, 0x000003FFUL, 0x000007FFUL, 0x00000FFFUL, 0x00001FFFUL, 0x00003FFFUL, 0x00007FFFUL, 0x0000FFFFUL, 0x0001FFFFUL, 0x0003FFFFUL, 0x0007FFFFUL, 0x000FFFFFUL, 0x001FFFFFUL, 0x003FFFFFUL, 0x007FFFFFUL, 0x00FFFFFFUL, 0x01FFFFFFUL, 0x03FFFFFFUL, 0x07FFFFFFUL, 0x0FFFFFFFUL, 0x1FFFFFFFUL, 0x3FFFFFFFUL, 0x7FFFFFFFUL, 0xFFFFFFFFUL } ; // Function: extract // Purpose: Extract bit field with specified position and width // Parameters: // position: Position of field's low order bit // width: Number of bits in bit field int extract(int value, int position, int width) { return( (value >> position) & mask[width-1] ) ; } int clear(int value, int position, int width) { return( (value & ~(mask[width-1] << position)) ) ; } int set(int value, int position, int width, int field) { int v ; v = clear(value, position, width) ; v = v | (field << position) ; return( v ) ; } void print_sizes() { char c ; short int s ; int i ; long int l ; float f ; double d ; cout << "Size of char: " << dec << sizeof(c) << endl ; cout << "Size of short: " << sizeof(s) << endl ; cout << "Size of int: " << sizeof(i) << endl ; cout << "Size of long: " << sizeof(l) << endl ; cout << "Size of float: " << sizeof(f) << endl ; cout << "Size of double: " << sizeof(d) << endl ; } main(int argc, char *argv[]) { int a, b, r, i ; a = 0x76543210 ; b = 0x33221100 ; /* for (i = 0 ; i < 32 ; i += 4) { cout << extract(a, i, 4) << showbase << hex << endl ; } for (i = 0 ; i < 32 ; i += 4) { cout << extract(b, i, 4) << showbase << hex << endl ; } */ a = 0xFFFFFFFF ; a = clear(a, 12, 4) ; cout << showbase << hex << a << endl ; a = clear(a, 4, 4) ; cout << showbase << hex << a << endl ; a = set(a, 12, 4, 1) ; a = set(a, 4, 4, 2) ; cout << showbase << hex << a << endl ; }