I am trying to create a message class with configurable as either 0 or 1 such as this
1 Byte, unit 8
Bit 0: Port A, 1 connected, 0 disconnected
Bit 1: Port A, 1 connected, 0 disconnected
Bit 2: Port A, 1 connected, 0 disconnected
Bit 3, 4, 5, 6, 7: Reserved
This I have been able to implement using union and type punning in C++ but this is seen as undefined behavior in C++.
union Msg{
uint8_t bitfield;
struct {
uint8_t PORTA : 1;
uint8_t PORTB : 1;
uint8_t PORTC : 1;
uint8_t : 5;
} msg;
};
How can I do this in C++?
And is it possible to create a function to pack data into this structure?
You can use bitwise operations. First, define helper functions for getting/setting a bit:
bool get_bit(uint8_t bits, uint8_t index) {
return bool((bits >> index) & 1U);
}
uint8_t set_bit(uint8_t bits, uint8_t index, bool value) {
return (bits & ~(1U << index)) | (uint8_t(value) << index);
}
Then, you can use uint8_t
instead of Msg
or define Msg
as an alias for uint8_t
.
// Msg is an alias for uint8_t
using Msg = uint8_t;
Msg message = 0;
message = set_bit(message, 0, true); // Setting the PORT A on
message = set_bit(message, 1, true); // Setting the PORT B on
message = set_bit(message, 2, false); // Setting the PORT C off
// You can use 1 or 0 instead of true or false
message = set_bit(message, 0, 0); // Setting the PORT A off
bool port_b = get_bit(message, 1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.