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