structs with uint8_t on a MCU without uint8_t datatype

怎甘沉沦 提交于 2019-12-01 05:20:11

Your compiler manual should describe how the bit fields are laid out. Read it carefully. There is something called __attribute__((byte_peripheral)) too that should help with packing bitfields sanely in memory-mapped devices.


If you're unsure about the bitfields, just use uint16_t for these fields and an access macro with bit shifts, for example

#define FIRST(x) ((x) >> 8)
#define SECOND(x) ((x) & 0xFF)

...
    uint16_t channel_type_and_id;
...

int channel_type = FIRST(x->channel_type_and_id);
int channel_id = SECOND(x->channel_type_and_id);

Then you just need to be sure of the byte-order of the platform. If you need to change endianness which the MCU seems to support? you can just redefine these macros.


A bitfield would most probably still be implemented in terms of bitshifts so there wouldn't be much savings - and if there are byte-access functions for registers, then a compiler would know to optimize x & 0xff to use them

According to the linked to compiler documentation byte access is through intrinsics

To access data in increments of 8 bits, use the __byte() and __mov_byte() intrinsics described in Section 7.5.6.

If you wanted to, you could make a new type to encapsulate how bytes should be accessed - something like a pair of bytes or a TwoByte class that will have the size of 16 bits.

For inspiration take a look at how std::bitset template class is implemented in STL for an analogue problem. https://en.cppreference.com/w/cpp/utility/bitset

As I posted in my other answer, I still believe the your bitfield could work - even though it might be platform specific. Basicly if it works out, the compiler should put in the correct bitshift operations.

The bitfield approach may work in practice. Although you do need some way to verify or make sure that it is packed in the correct way for your target platform. The bitfield approach will not be portable as you state yourself the order of bitfields is platform dependent.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!