Split up 8 byte wrappers from generic bit array functions.
[apps/agl-service-can-low-level.git] / src / bitfield / 8byte.h
1 #ifndef __8BYTE_H__
2 #define __8BYTE_H__
3
4 #include <stdint.h>
5 #include <stdbool.h>
6
7 #ifdef __cplusplus
8 extern "C" {
9 #endif
10
11 // TODO using uint64_t everywhere for CAN message payload is kind of cute, but
12 // in actuality a CAN message may have a smaller payload, and it makes all of
13 // these functions not applicable to other data sizes. It's also fairly
14 // inefficient on 32-bit platforms. how much work is it to switch vi-firmware
15 // to using uint8_t*?
16
17 /* Public: Reads a subset of bits from a byte array.
18  *
19  * data - the bytes in question.
20  * startPos - the starting index of the bit field (beginning from 0).
21  * numBits - the width of the bit field to extract.
22  * bigEndian - if the data passed in is little endian, set this to false and it
23  *      will be flipped before grabbing the bit field.
24  *
25  * Bit fields are positioned according to big-endian bit layout, but inside the
26  * bit field, values are represented as little-endian. Therefore, to get the bit
27  * field, we swap the overall byte order if bigEndian == false and
28  * use the value we find in the field (assuming the embedded platform is little
29  * endian).
30  *
31  * For example, the bit layout of the value "42" (i.e. 00101010 set at position
32  * 14 with length 6 is:
33  *
34  *     000000000000001010100000000000000000000000000000000000000000000
35  *
36  * and the same value and position but with length 8 is:
37  *
38  *     000000000000000010101000000000000000000000000000000000000000000
39  *
40  * If the architecture where is code is running is little-endian, the input data
41  * will be swapped before grabbing the bit field.
42  *
43  * Examples
44  *
45  *  uint64_t value = getBitField(data, 2, 4);
46  *
47  * Returns the value of the requested bit field.
48  */
49 uint64_t getBitField(uint64_t data, const uint16_t startPos,
50         const uint16_t numBits, bool bigEndian);
51
52 /* Public: Set the bit field in the given data array to the new value.
53  *
54  * data - a byte array with size at least startPos + numBits.
55  * value - the value to set in the bit field.
56  * startPos - the starting index of the bit field (beginning from 0).
57  */
58 void setBitField(uint64_t* data, uint64_t value, const uint16_t startPos,
59         const uint16_t numBits);
60
61 /* Public: Retreive the nth byte out of 8 bytes in a uint64_t.
62  *
63  * source - the source data to retreive the byte from.
64  * byteNum - the index of the byte, starting at 0 and assuming big-endian order.
65  *
66  * Returns the requested byte from the source bytes.
67  */
68 uint8_t nthByte(const uint64_t source, const uint16_t byteNum);
69
70 #ifdef __cplusplus
71 }
72 #endif
73
74 #endif // __8BYTE_H__