1// 2// bitfield.c - extract and set bit fields 3// 4// Written by Eryk Vershen 5// 6// See comments in bitfield.h 7// 8 9/* 10 * Copyright 1996, 1997 by Apple Computer, Inc. 11 * All Rights Reserved 12 * 13 * Permission to use, copy, modify, and distribute this software and 14 * its documentation for any purpose and without fee is hereby granted, 15 * provided that the above copyright notice appears in all copies and 16 * that both the copyright notice and this permission notice appear in 17 * supporting documentation. 18 * 19 * APPLE COMPUTER DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE 20 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 21 * FOR A PARTICULAR PURPOSE. 22 * 23 * IN NO EVENT SHALL APPLE COMPUTER BE LIABLE FOR ANY SPECIAL, INDIRECT, OR 24 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM 25 * LOSS OF USE, DATA OR PROFITS, WHETHER IN ACTION OF CONTRACT, 26 * NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION 27 * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 28 */ 29 30#include "bitfield.h" 31 32 33// 34// Defines 35// 36 37 38// 39// Types 40// 41 42 43// 44// Global Constants 45// 46const unsigned int masks[] = { 47 0x00000000, 48 0x00000001, 0x00000003, 0x00000007, 0x0000000F, 49 0x0000001F, 0x0000003F, 0x0000007F, 0x000000FF, 50 0x000001FF, 0x000003FF, 0x000007FF, 0x00000FFF, 51 0x00001FFF, 0x00003FFF, 0x00007FFF, 0x0000FFFF, 52 0x0001FFFF, 0x0003FFFF, 0x0007FFFF, 0x000FFFFF, 53 0x001FFFFF, 0x003FFFFF, 0x007FFFFF, 0x00FFFFFF, 54 0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF, 0x0FFFFFFF, 55 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF, 0xFFFFFFFF 56}; 57 58 59// 60// Global Variables 61// 62 63 64// 65// Forward declarations 66// 67 68 69// 70// Routines 71// 72unsigned int 73bitfield_set(unsigned int *bf, int base, int length, unsigned int value) 74{ 75 unsigned int t; 76 unsigned int m; 77 int s; 78 79 // compute shift & mask, coerce value to correct number of bits, 80 // zap the old bits and stuff the new value 81 // return the masked value in case someone wants it. 82 s = (base + 1) - length; 83 m = masks[length]; 84 t = value & m; 85 *bf = (*bf & ~(m << s)) | (t << s); 86 return t; 87} 88 89 90unsigned int 91bitfield_get(unsigned int bf, int base, int length) 92{ 93 unsigned int m; 94 int s; 95 96 // compute shift & mask 97 // return the correct number of bits (shifted to low end) 98 s = (base + 1) - length; 99 m = masks[length]; 100 return ((bf >> s) & m); 101} 102