5 * th9x - http://code.google.com/p/th9x
6 * er9x - http://code.google.com/p/er9x
7 * gruvin9x - http://code.google.com/p/gruvin9x
9 * This file is based on work published at http://www.coranac.com/documents/working-with-bits-and-bitfields
11 * License GPLv2: http://www.gnu.org/licenses/gpl-2.0.html
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License version 2 as
15 * published by the Free Software Foundation.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
28 // A set of bitfield handling macros
31 inline T
bfBit(uint8_t n
)
36 #define BFBIT_SET(y, mask) ( y |= (mask) )
37 #define BFBIT_CLEAR(y, mask) ( y &= ~(mask) )
38 #define BFBIT_FLIP(y, mask) ( y ^= (mask) )
39 #define BF_SINGLE_BIT_SET(y, i) BFBIT_SET(y, bfBit(i))
41 //! Create a bitmask of length 'len'.
43 inline T
bfBitmask(uint8_t len
)
45 return bfBit
<T
>(len
) - 1;
48 //! Create a bitfield mask of length 'len' starting at bit 'start'.
50 inline T
bfMask(uint8_t start
, uint8_t len
)
52 return bfBitmask
<T
>(len
) << start
;
55 //! Prepare a bitmask for insertion or combining.
57 inline T
bfPrep(T x
, uint8_t start
, uint8_t len
)
59 return (x
& bfBitmask
<T
>(len
)) << start
;
62 //! Extract a bitfield of length 'len' starting at bit 'start' from 'y'.
64 inline T
bfGet(T y
, uint8_t start
, uint8_t len
)
66 return ((y
)>>(start
)) & bfBitmask
<T
>(len
);
69 //! Insert 'len' bits of 'x 'into 'y', starting at bit 'start' from 'y'.
71 inline T
bfSet(T to
, T from
, uint8_t start
, uint8_t len
)
73 return (to
& ~bfMask
<T
>(start
, len
)) | bfPrep
<T
>(from
, start
, len
);
77 inline T
bfBitGet(T y
, T mask
)
83 inline T
bfSingleBitGet(T y
, uint8_t i
)
85 return bfBitGet(y
, bfBit
<T
>(i
));