27766733fe37b5969a66d494a15a32278e950773
[apps/agl-service-can-low-level.git] / src / bitfield / bitfield.h
1 #ifndef __BITFIELD_H__
2 #define __BITFIELD_H__
3
4 #include <stdint.h>
5 #include <stdbool.h>
6
7 /* Public: Reads a subset of bits from a byte array.
8  *
9  * data - the bytes in question.
10  * startPos - the starting index of the bit field (beginning from 0).
11  * numBits - the width of the bit field to extract.
12  * bigEndian - if the data passed in is little endian, set this to false and it
13  *      will be flipped before grabbing the bit field.
14  *
15  * Bit fields are positioned according to big-endian bit layout, but inside the
16  * bit field, values are represented as little-endian. Therefore, to get the bit
17  * field, we swap the overall byte order if bigEndian == false and
18  * use the value we find in the field (assuming the embedded platform is little
19  * endian).
20  *
21  * For example, the bit layout of the value "42" (i.e. 00101010 set at position
22  * 14 with length 6 is:
23  *
24  *     000000000000001010100000000000000000000000000000000000000000000
25  *
26  * and the same value and position but with length 8 is:
27  *
28  *     000000000000000010101000000000000000000000000000000000000000000
29  *
30  * If the architecture where is code is running is little-endian, the input data
31  * will be swapped before grabbing the bit field.
32  *
33  * Examples
34  *
35  *  uint64_t value = getBitField(data, 2, 4);
36  *
37  * Returns the value of the requested bit field.
38  */
39 uint64_t getBitField(uint64_t data, int startPos, int numBits, bool bigEndian);
40
41 /* Public: Set the bit field in the given data array to the new value.
42  *
43  * data - a byte array with size at least startPos + numBits.
44  * value - the value to set in the bit field.
45  * startPos - the starting index of the bit field (beginning from 0).
46  */
47 void setBitField(uint64_t* data, uint64_t value, int startPos, int numBits);
48
49 /* Public: Retreive the nth byte out of 8 bytes in a uint64_t.
50  *
51  * source - the source data to retreive the byte from.
52  * byteNum - the index of the byte, starting at 0 and assuming big-endian order.
53  *
54  * Returns the requested byte from the source bytes.
55  */
56 uint8_t nthByte(uint64_t source, int byteNum);
57
58 #endif // __BITFIELD_H__