Various fixes around Companion trainer mode (#7116)
[opentx.git] / radio / src / bitfield.h
bloba0c753e0f2744a8392f63227667d2744066e018d
1 /*
2 * Copyright (C) OpenTX
4 * Based on code named
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.
23 #ifndef BITFIELD_H
24 #define BITFIELD_H
26 #include <inttypes.h>
28 // A set of bitfield handling macros
30 template <typename T>
31 inline T bfBit(uint8_t n)
33 return T(1) << 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'.
42 template <typename T>
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'.
49 template <typename T>
50 inline T bfMask(uint8_t start, uint8_t len)
52 return bfBitmask<T>(len) << start;
55 //! Prepare a bitmask for insertion or combining.
56 template <typename T>
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'.
63 template <typename T>
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'.
70 template <class T>
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);
76 template <class T>
77 inline T bfBitGet(T y, T mask)
79 return (y & mask);
82 template <class T>
83 inline T bfSingleBitGet(T y, uint8_t i)
85 return bfBitGet(y, bfBit<T>(i));
88 #endif //BITFIELD_H