]> rtime.felk.cvut.cz Git - pes-rpp/rpp-lib.git/blob - rpp/include/binary.h
Fixed documentation and minor bug fixes.
[pes-rpp/rpp-lib.git] / rpp / include / binary.h
1 /**
2  * RPP binary handling header file.
3  * This file contains helpful macros for binary and bit manipulation.
4  *
5  * @file binary.h
6  *
7  * @copyright Copyright (C) 2013 Czech Technical University in Prague
8  *
9  * @author Carlos Jenkins <carlos@jenkins.co.cr>
10  */
11
12 #ifndef __RPP_BINARY_H
13 #define __RPP_BINARY_H
14
15 // Discussion about binary macros here:
16 // http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&t=60729
17
18 /**
19  * Create a bit mask for given bit number.
20  * For example:
21  *  - _BV(7) -> B[0100 0000]
22  *  - _BV(1) -> B[0000 0010]
23  *  - _BV(0) -> B[0000 0001]
24  *
25  * The function name stands for Bit Value, in reference that the mask is created
26  * only with the given bit number set.
27  *
28  * @param[in] bit       Bit number to create the mask, starting at 0 for the
29  *                      least-significant (rightmost) bit.
30  *
31  * @return A mask with all bits clear except the given bit number.
32  */
33 #define _BV(bit) (1UL << (bit))
34
35 /**
36  * Reads a bit of a number.
37  *
38  * @param[out] value    The number from which to read.
39  * @param[in] bit       Which bit to read, starting at 0 for the
40  *                      least-significant (rightmost) bit.
41  *
42  * @return The value of the bit (0 or 1).
43  */
44 #define bit_read(value, bit) (((value) >> (bit)) & 0x01)
45
46
47 /**
48  * Sets (writes a 1 to) a bit of a numeric variable.
49  *
50  * @param[out] value    The numeric variable whose bit to set.
51  * @param[in] bit       Which bit to set, starting at 0 for the
52  *                      least-significant (rightmost) bit
53  *
54  * @return None.
55  */
56 #define bit_set(value, bit) ((value) |= (1UL << (bit)))
57
58
59 /**
60  * Clears (writes a 0 to) a bit of a numeric variable.
61  *
62  * @param[out] value    The numeric variable whose bit to clear.
63  * @param[in] bit       Which bit to clear, starting at 0 for the
64  *                      least-significant (rightmost) bit.
65  *
66  * @return None.
67  */
68 #define bit_clear(value, bit) ((value) &= ~(1UL << (bit)))
69
70
71 /**
72  * Writes a bit of a numeric variable.
73  *
74  * @param[out] value    The numeric variable to which to write.
75  * @param[in] bit       Which bit of the number to write, starting at 0 for the
76  *                      least-significant (rightmost) bit.
77  * @param[in] bit_value The value to write to the bit (0 or 1).
78  *
79  * @return None.
80  */
81 #define bit_write(value, bit, bit_value) (bit_value ? bit_set(value, bit) : bit_clear(value, bit))
82
83
84 #endif /* __RPP_BINARY_H */