1 /* 2 * Created by Ian "Goober5000" Warfield for the FreeSpace2 Source Code Project. 3 * You may not sell or otherwise commercially exploit the source or things you 4 * create based on the source. 5 */ 6 7 8 9 #ifndef _BIT_ARRAY_H 10 #define _BIT_ARRAY_H 11 12 #include "globalincs/pstypes.h" 13 14 15 // the following four functions are adapted from http://www.codeproject.com/cpp/BitArray.asp; their explanation 16 // is as follows: 17 /* 18 * The Bit Array structure provides a compacted arrays of Booleans, with one bit for each Boolean value. 19 * A 0 (1) bit corresponds to the Boolean value false (true), respectively. We can look at a stream of bytes 20 * as a stream of bits; each byte contains 8 bits, so any n bytes hold n*8 bits. And the operation to 21 * manipulate this stream or bit array is so easy, just read or change the bit's state or make any Boolean 22 * operation on the whole bits array, like �AND�, �OR�, or �XOR�. 23 * 24 * As each byte contains 8 bits, we need to divide the bit number by 8 to reach the byte that holds the bit. 25 * Then, we can seek to the right bit in the reached byte by the remainder of dividing the bit number by 8. 26 * So to read or change the bit state, the operations will be like that. 27 * 28 * Note that to divide by 8, we need only to shift right by 3 (>>3), and to get the remainder of dividing 29 * by 8, we need only to AND with 7 (&7). 30 */ 31 32 // returns bit state (0 or 1) 33 #define get_bit(array, bitnum) ((((ubyte *) array)[(bitnum) >> 3] >> ((bitnum) & 7)) & 1) 34 35 // sets bit to 1 36 #define set_bit(array, bitnum) (((ubyte *) array)[(bitnum) >> 3] |= (1 << ((bitnum) & 7))) 37 38 // clears bit to 0 39 #define clear_bit(array, bitnum) (((ubyte *) array)[(bitnum) >> 3] &= ~(1 << ((bitnum) & 7))) 40 41 // toggles bit (xor) 42 #define toggle_bit(array, bitnum) (((ubyte *) array)[(bitnum) >> 3] ^= (1 << ((bitnum) & 7))) 43 44 45 // calculate number of bytes from number of bits 46 #define calculate_num_bytes(num_bits) ((num_bits >> 3) + 1) 47 48 49 #endif // _BIT_ARRAY_H 50