r/embedded • u/J_Bahstan • Jan 10 '26
Every embedded Engineer should know this trick
https://github.com/jhynes94/C_BitPacking
A old school Senior Principal engineer taught me this. Every C curriculum should teach it. I know it's a feature offered by the compiler but it should be built into the language, it's too good.
192
u/Well-WhatHadHappened 25+ Years Jan 10 '26
I don't think I've ever met an engineer who didn't know that...
48
u/furssher Jan 10 '26
Lol Reddit in a nutshell. On one end of the Reddit spectrum, so many people are cheering the demise of Stack Overflow because of its unwelcoming and condescending attitude toward the people it was meant to help.
Then you have this comment which belittles a cool embedded trick that OP just learned and wanted to share with the rest of the embedded community.
Never change Reddit.
20
u/felafrom Jan 10 '26
I don't think the parent comment is belittling in nature. All sorts and levels of engineers on this very thread, and consequently all sorts of opinions.
I learned this the first thing when I was an intern. I believe any embedded engineer worth their salt would know at least this much, and likely a couple "personal" flavors on top of this depending on the ABI/portability/compiler variations.
As much as I like this thread and the proliferation of solid baseline practices, there's not always an emotional value attached to the idea of wanting to engineer something well.
3
u/T_D707 Jan 10 '26
“Any engineer worth their salt would know this” no that doesn’t sound belittling at all
2
0
u/armeg Jan 10 '26
Man, I guess I just am not worth any salt and should just quit. I didn't know this existed until this post. I started work on our IoT project to supplement my main business and did not come from a C background, I've had to teach myself everything about it.
1
2
u/J_Bahstan Jan 10 '26
This was my thought exactly. Thank you for comment. It was the first comment on the post by "Well-WhatHadHappened" and thought I was an idiot for a second there.
Appreciate it man, thank you
1
u/ihatemovingparts Jan 11 '26
Then you have this comment which belittles a cool embedded trick that OP just learned and wanted to share with the rest of the embedded community.
And then you have the title: Every embedded Engineer should know this trick.
Yeah because it's a pretty basic and long-standing part of C. It also carries risks and challenges. I dislike the macro soup that gets recommended instead, but that is a much more predictable way of going about things.
82
96
u/Relevant-Team-7429 Jan 10 '26
I am about to graduate, no one tought me this
6
u/Cathierino Jan 11 '26
For a good reason. Though it would be better to teach why you probably shouldn't do this instead of skipping it entirely so you don't end up discovering it on your own and then wondering why you have bugs out of nowhere down the line.
I am guilty of using it myself though but that's because I know the obscure compile tools I am using will never be updated again and potentially change how bit fields and unions are handled.
22
→ More replies (2)2
u/lllorrr Jan 11 '26
At some point of your personal growth you'll have to read and understand C standard. Better to do that sooner than later. With this new knowledge you will understand why they didn't teach you this. Short summary: this is undefined behavior. There is no guarantee whatsoever what will happen during compilation and runtime. Today it may work as you expect, tomorrow it will do something completely unexpected.
8
u/legodfrey Jan 10 '26
Had to teach a Senior engineer this just before Christmas 😮💨
8
u/andypanty69 Jan 10 '26
Not every one knows this stuff but then some of the ignorance comes from knowledge of how computers work not being taught. Programming has been seen as too high a level for at least 2 decades for many programmer's to require hardware knowledge. Try mentioning cache lines to a java programmer.
1
u/michael9dk Jan 10 '26
Too much gets abstracted away for convenience.
When you get used to high-level programming, you automatically pick the easiest/familiar way. With modern computers, you don't have to bother with structs when you have classes. But that view changes, when you are restricted in embedded development.
(my point of view as a full-stack C# developer, while refreshing my EE books from the 90's)
1
3
2
u/Nerdz2300 Jan 10 '26
Im a hobbyist and I have no clue what this does so Im gonna read up on Unions (not the labor kind) lol.
2
u/falafelspringrolls Jan 10 '26
I'm old enough to remember embedded being a bare-metal only field, where bit fields are second nature. These days I can imagine some newer embedded engineers have never stepped away from quad core linux SOM's
1
u/Well-WhatHadHappened 25+ Years Jan 10 '26 edited Jan 10 '26
Well... The Linux Kernel uses bitfields all over the place.
The main scheduler structure is one place that I can think of right off the top of my head... I think the TCP stack has a bunch as well.
These aren't some abstract thing no one ever uses, and they're in no way limited to bare metal embedded work.
4
u/TT_207 Jan 10 '26
Honestly never used this. Always used defines for bits or shifts and done it that way.
I have used pragmas to force byte alignment though for structs.
3
1
u/FrostyMaterial4135 Jan 27 '26
Maybe not, but this whole thread highlighted all the wasteful engineers declaring 64 bytes for a 8 byte data structure. Did new engineers forget about bits?
1
u/Delengowski Jan 10 '26
I graduated ECE and didn't know this.
When it comes time to set the register what I am doing now?
Like I want to mask the register with the bits under
reg.s
What do I do? The mask off of it? Or do I do hw field.
3
u/Well-WhatHadHappened 25+ Years Jan 10 '26 edited Jan 10 '26
For most C compilers, 'hw' will be the concatenated 8 bits of 's'
Struct packing and bitfields (and unions to some extent) are compiler/platform specific though, so it's important to understand how your compiler works.
2
u/Delengowski Jan 10 '26
Oh I'm getting it now. Since its a union and we're packing the struct... gotcha, thanks
1
20
u/furdog_grey Jan 10 '26
No! Please! This "trick" shouldn't be used anywhere seriously.
C doesn't have feature like this, and squeezing it out of implementation specific behaviour is plain dumb. See MISRA C:2023 Rule 6.3: A bit field shall not be declared as a member of a union. It explains specific reason why you should never use it.
If such "trick" will never face anything other than your own personal project, i guess it's fine.
1
u/J_Bahstan Jan 10 '26
This "trick" is running right now 1.2 million medical devices and controlling mission critical servo motor drives.
I love your comment and it's true it must be used carefully due to the compiler & hardware considerations. Overall, it's a great way to write code and I strongly recommend people use it.
2
u/joebeazelman Jan 11 '26
Yup. Those devices, drives, air traffic control systems, and fighter jets are written in using the same tricks, but using Ada instead of C.
4
u/Global_Struggle1913 Jan 10 '26 edited Jan 10 '26
This is the reason why blindly using MISRA is a source of badly readable code.
Using structs for this is widely used within the industry without a single problem.
Just verify every new compiler release once and then go for it.
5
u/furdog_grey Jan 10 '26
That's why i said "using this in your own project" is probably fine. If you're able to prove consistency and safety of the code - this is on you and on your company. But otherwise the code is bound to the compiler and specific hardware, which automatically makes it non-portable in the best case.
3
u/Global_Struggle1913 Jan 10 '26 edited Jan 10 '26
But otherwise the code is bound to the compiler and specific hardware, which automatically makes it non-portable in the best case.
No drama.. 70% is the industry is GCC, 20% LLVM and a couple of niches with exotic compilers where MISRA&Co. most likely must be followed due to certification requirements.
14
u/Thor-x86_128 Low-level Programmer Jan 10 '26
Those brightness fields can be optimized as 2 bits enum
13
u/ProfessorDonuts Jan 10 '26
For context for those curious, what they are referring to is a register definition like this
typedef enum { BRIGHTNESS_LOW = 0b00, BRIGHTNESS_NORMAL = 0b01, BRIGHTNESS_HIGH = 0b10, BRIGHTNESS_MAX = 0b11 // reserved/invalid } brightness_t; union EXAMPLE_REGISTER { uint8_t hw; struct __attribute__((packed)) { uint8_t IDLE : 1; // bit 0 uint8_t BRIGHTNESS : 2; // bits 1–2 uint8_t PARTY_MODE : 1; // bit 3 uint8_t DEBUG_MODE : 1; // bit 4 uint8_t RESERVED : 2; // bits 5–6 uint8_t FACTORY_TEST_MODE : 1; // bit 7 } s; };and brightness can be set as
reg.s.BRIGHTNESS = BRIGHTNESS_HIGH;and set bits[1:2] with correct mask.
4
u/leguminousCultivator Jan 10 '26
You can go a step further and make the BRIGHTNESS field the enum type directly. That keeps use of the field in either direction as the enum inherently.
1
u/KillingMurakami Jan 10 '26
This is assuming the enum_type is seen by the compiler as 8-bit wide?
3
u/mustbeset Jan 10 '26
That's why you have to read the compiler manual. It's ok to write low level code that's compiler dependent. But if you change compiler (or even major version) you should check if the behaviour is still the same. Unittest for the win (and maybe a small processer testbench)
2
u/KillingMurakami Jan 10 '26
This is exactly why I asked! I was expecting that caveat in OP's comment. IIRC, an enum isn't even guaranteed to always be unsigned
1
2
1
9
u/Any-Association-3674 Jan 10 '26
You are right, this is how it must be done - it's not an optimization, it's the correct implementation. Otherwise, you may end up with conflicting values in your register (e.g. both LOW and HIGH brightness in the same time)
1
1
u/J_Bahstan Jan 10 '26
Agreed.
Just wrote this as a made up example. The code I actively use it in is closed source.
2
u/hey-im-root Jan 13 '26
Texas Instruments uses this for the HAL on their C2000 series. I’ve wanted to make an ATtiny85 library using a similar setup and everyone on Reddit was like noooo lol
1
78
u/Allan-H Jan 10 '26 edited Jan 10 '26
I remember doing something like that in the early '90s and thinking how cool it was.
Then my code broke when the compiler was updated to a new version. I complained to the compiler authors, and they (rightly) replied that the C standard did not define an order for bit fields and it was my fault for writing something that was not portable.
I haven't use bit fields since. It's unlikely that C will ever be fixed and I rarely write code in C any more.
6
u/electricity-wizard Jan 11 '26
It’s a real shame. Because this is exactly what I want bitfields for! But the fact you can not trust the underlying memory layout for this makes writing registers in bitfields bad.
2
u/rsaxvc Jan 12 '26
Ooh, what compiler was that?
2
u/Allan-H Jan 12 '26
Hi-Tech C. They had C compilers for a number of microcontrollers. I was using their i8051 C compiler. Later they were bought by Microchip and they dropped all but the PIC compiler.
1
u/Ok_6970 Mar 26 '26
Did Microchip ever do something correct?
1
u/Large-Style-8355 May 10 '26
I was big in hating Microchip as well because I had wasted time with PIC16... Years later I got the lead Firmware developer of a product family of high performance remote controls - which was "unfortunately" build around PIC32 hardware. But guess what? It turned out to be a way better experience then I had all the years before building Embedded Systems based on AVR, MSP16, C166, Phillips/NXP, STM32 etc PIC32 hardware architecture was designed so clean, straight forward, smart, predictable, exactly the same over a large portfolio of controllers from small to large, the toolchain just being a "commercial" gnu tool chain. It was a real joy working in the ecosystem. STM32 in contrast pretty often even had changed behaviour within two chips with the exact same part number except the last letter which should just be a date code. They just changed UART or RTC behaviour in a way your battle proven code breaks. And don't lete start with STMs HAL. It raver should be named Hell. A ton of libraries and code which looks like they've implemented all the basic and the advanced things. I often saw "locking mechanisms" in HAL code which lead the naive user getting the impression that stuff is thread and interrupt safe. But that was just bullshit architecture - there was literally tons of (UN)lock_ressource() in Hardware driver code like UART, USB etc. Demos worked - but put under a little bit more stress they fell just apart. Turns out the locking code just sets /unsets a variable is_locked - without preventing another thread, an interrupt, a high prio interrupt doing the exact same thing.
166
u/Codetector Jan 10 '26
If you do this make sure you add a static assert for the size of the struct. Because there is no guarantee that this gets packed correctly.
4
u/free__coffee Jan 10 '26
Thats not possible, right? The compiler will place it at the nearest byte of address space, since it needs to fit the entire 8-bit variable. And since it is “packed”, all 8 bitfields will be placed in the same byte, right?
The byte-variable makes it so that the data is aligned properly
Also, what is the purpose of the “static” modifier? I don’t see the purpose
72
u/Codetector Jan 10 '26
Static_assert is a compile time assertion. It does not generate any real code at run time. If you read the C spec, the compiler is free to ignore the bit fields. So technically it would not be wrong to have each of the field take up a whole byte.
27
u/SAI_Peregrinus Jan 10 '26
The packed attribute is not standard C.
static_assertis standard inassert.hin C11 & C17, the header is unneded in C23. "static" isn't a modifier, it's part of the name since it's a compile-time assertion instead of runtime.1
u/Advanced-Theme144 Jan 11 '26
Had no clue static assertions even existed until know, this could really help with a lot of my own compile time issues when building between ARM and x86
82
u/Current-Fig8840 Jan 10 '26
This is normal knowledge for Embedded. Just don’t forget that bit order is determined by compiler ABI.
6
u/Laistytuviukas Jan 11 '26
This is normal knowledge for high level languages as C# too - flags attribute. Seems like normal knowledge overall.
126
u/tobi_wan Jan 10 '26
And one should also know disadvantages of it. For describing registers and using only at the low level of the driver it is okay. As the code is not guaranteed to be portable , you can not point to members and no guarantee that the bit operations can be implemented efficiently for other things bit Fields can be a pain
49
u/BastetFurry RP2040 Jan 10 '26
If you do stuff like this you don't aim for portability, that is a myth anyway. In the real world you get the cheapest MCU the company can procure thrown on your table and then you have to make the magic happen.
27
u/kdt912 Jan 10 '26
Well yes until 5 years down the line the company decides they want to swap MCUs to a different vendor for their next refresh of the product and now you’re cursing yourself out for writing it so platform dependent. Just happened to us and slowed the porting over down a bit because we had to find where missing features broke things
9
2
u/BastetFurry RP2040 Jan 10 '26
But that is your bosses problem, not yours. If they don't ask the people on the proverbial floor what would be best then you can only do what you are told, and when they think that the 10 cent MCU from Vendor A needs to be replaced with the 8 cent MCU from Vendor B then you can only shrug, throw in a bunch of defines for when the other vendor is cheaper again and call it a day.
1
15
u/tobi_wan Jan 10 '26
That depends on the industry honestly, in the last.l 20 years I switched a lot the system in the same product and since COVID and we issue of not getting parts flexibility is for some industries nowadays more important
→ More replies (11)1
u/Jaded_Spot6858 Mar 28 '26
What does portable mean? We are doing this packing in my science club between STM32 and linux because we want CANbus to be as light as possible. What does portability mean? The documentation for "(packed)" is shit and often leaves with more questions than answers.
For example I know that i shouldn't do mixing of different sizes like:
uint16 : 9
uint8 :2
int16 : 10
But what does portabiltiy mean?
72
u/nekokattt Jan 10 '26 edited Jan 10 '26
bitshifting is still more portable, less likely to delve into the realm of unintended side effects, compiler specifics, and you can use some macros to make it easier to read if bit fiddling isn't what you like to look at.
It isn't as pretty, but a decent compiler will still optimise as well as possible.
#define GET_BIT(value, mask) ((value) & (mask) != 0)
#define SET_BIT(value, mask) ((value) | (mask))
#define UNSET_BIT(value, mask) ((value) & ~(mask))
#define BIT(n) (1 << (n))
#define UNSET (0)
#define BRIGHTNESS BIT(0)
#define RED BIT(1)
#define GREEN BIT(2)
#define BLUE BIT(3)
#define FLASH BIT(4)
typedef uint8_t register_t;
...
register_t value = UNSET;
value = SET_BIT(value, BRIGHTNESS);
value = SET_BIT(value, GREEN);
...
if (GET_BIT(value, RED)) {
value = UNSET_BIT(value, BLUE);
}20
u/jmiguelff Jan 10 '26
I prefer it this way.. I understand there may be a super specific case where unions are better.. but bitshifting is my goto.
→ More replies (2)2
u/RedEd024 Jan 11 '26
It’s a union, you can shift the uint8_t variable. The union define will define what each bit it used for… in other words, two things can be true
1
20
u/readmodifywrite Jan 10 '26
We do know it, and we have reasons that we tend not to use it. The C standard doesn't guarantee the order of a bit field, and usually what we specifically need in embedded is a guaranteed bit order.
The traditional bit shifting technique guarantees ordering and makes it a thing we don't have to worry about.
In practice, if GCC is yielding the order you need, then it's fine. But it isn't portable which is why you usually won't see it in a vendor library. And if you ever upgrade GCC remember they can change the way the bit field is ordered because the C standard doesn't require any specific ordering.
The packed attribute is incredibly useful though, everyone should know that one (but who in embedded doesn't?)
4
u/Kevlar-700 Jan 11 '26
Ada does this in a much nicer way and for any sized registers (e.g. 2 bits) and it's absolutely portable.
2
u/readmodifywrite Jan 11 '26
I've been wanting to learn Ada for decades! It is one of my gotos for very well designed languages. The bounded types are really cool, in/out args, very clearly laid out code, does everything we wish C could do but better than C would have done it.
It just doesn't have good compiler support in my niche and nobody uses it. Such a shame.
2
u/Kevlar-700 Jan 11 '26
There is Gnat GCC and Gnat LLVM which support most targets well. You might have to write drivers or use C drivers. Perhaps you mean runtime. The light runtime supports many targets (e.g. there is a light-cortex-m3) but you won't have tasking, exception propagation or protected objects.
2
u/readmodifywrite Jan 11 '26
Yeah, I'm running Xtensa, RISC-V, and ARM Cortex-M chips all on the same system, all with extensive legacy C libraries.
I could probably live without the runtime though...
2
13
u/olawlor Jan 10 '26
In the 1990's I wrote thousands of lines of bitfield declarations ... on a big-endian machine. That code, even when dealing with 8-bit values, gets the wrong bits on a little-endian machine.
Use bitshifts instead of bitfields if your code needs to be portable.
8
u/manystripes Jan 10 '26
Some TI compilers give you a compiler flag to swap the bit order, so even targeting a single platform isn't guaranteed to have the same bit order from project to project.
3
u/supersonic_528 Jan 11 '26
That code, even when dealing with 8-bit values, gets the wrong bits on a little-endian machine.
I'm guessing this is a compiler thing and not endianness related.
4
u/olawlor Jan 11 '26
The same compiler (gcc) puts the first bit in a bitfield in the low-order bit on a little-endian machine (like x86), but in the high-order bit on a big-endian machine (PowerPC). (There's an option inside gcc called "BITS_BIG_ENDIAN", specific to the platform.)
Conceptually unrelated to byte order, but in practice seems to be linked.
11
u/N_T_F_D STM32 Jan 10 '26 edited Jan 10 '26
You can go one step further and not give a name to the struct, then you can access its elements as if they were elements of the top level union type (it's a GCC extension, works with clang and probably others too)
7
u/EkriirkE Bare Metal Jan 10 '26
This is called a anonymous union or struct. I also use these all the time
11
u/H1BNOT4ME Jan 10 '26 edited Jan 11 '26
I had a chuckle reading this post. Ada--the most slept on language--has had a far superior construct with type checking and a variety of operating modes since 1983! It's also portable!
On some hardware, reading a memory value has side effects. Atomic lets you read, write, or modify it in one operation, while Volatile prevents the compiler from caching or optimizing operations. In C and C++, you couldn't control whether the compiler generates an atomic increment until 2011.
type Example_Register is record
Idle : Boolean; -- bit 0
Low_Brightness : Boolean; -- bit 1
Normal_Brightness. : Boolean; -- bit 2
High_Brightness : Boolean; -- bit 3
Party_Mode : Boolean; -- bit 4
Debug_Mode : Boolean; -- bit 5
Reserved : Boolean; -- bit 6
Factory_Test_Mode : Boolean; -- bit 7
end record with
Pack, -- ← remove padding between fields
Size => 8, -- Total size in bits (compiler checks it fits)
Object_Size => 8, -- Size of stand-alone objects
Volatile => True, -- Needed for hardware registers
Volatile_Components => True, -- All components are volatile (alt)
Atomic => True, -- Read-modify-write must be atomic (stronger)
Independent_Components => True, -- Components independently accessible
Default_Value => (others => <>), -- Default initialization value (none)
Suppress_Initialization => True; -- Skip default init3
2
u/Kevlar-700 Jan 11 '26
Quite hilarious reading the comments after using Ada for embedded and I would have agreed with them ~4 years ago 🥂 🍿
2
u/CuriousChristov Jan 11 '26
Don't you need a Record_Representation_Clause and Bit_Order attribute to make it truly portable? I remember using that to read big-endian data structures on a x86 platform with no problem.
This is still so much better than bit shifts for clarity and comparison to a data sheet or spec that it's not even funny.
1
u/Kevlar-700 Jan 11 '26
Yes and often volatile_full_access is needed by the hardware which solves another issue brought up in some comments. Of course Ada has precision types (any bit size). Which is probably needed to makes it always work well as a consistent separation of concern and may explain why C++ hasn't made this work.
1
u/H1BNOT4ME Jan 11 '26 edited Jan 11 '26
Great question! When you write a record representation clause without specifying
Bit_Order, the compiler uses the platform's default bit ordering. This means your code is portable in the sense that it automatically follows the native conventions of the target — Ada abstracts away the difference for you. So it's portable.While it sounds like semantics, you instead might be asking if it can be made non portable. Quite often your code will need to interface with external platform or data with a different endianness. In that case, you would add a representation clause to fix it to a specific endianness using
Bit_Order.What's really cool is that the compiler automatically handles endianness conversions for you by deriving from an internal type and changing its bit order:
type Intel_Example_Register is New Example_Register; for Intel_Example_Register'Bit_Order use High_Order_First; -- x86 register Host : Example_Register; Target : Intel_Example_Register; -- Ada isn't C/C++, casting is required. Host := Example_Register(Target); Target := Intel_Example_Register(Host);Can C, C++, or Rust do that?
MIKE DROP!!!!
2
u/Amazing-Eye9876 Jan 11 '26
Wow! A coworker sent me your comment, and this is the first time I’ve ever fallen in love with a language at first sight. That’s saying something coming from a promiscuous programmer who regularly cheats on C/C++ with dozens of other languages. Ada’s code is elegant, clean, and pleasant to read. You can tell an incredible amount of thought went into its design.
I remember back in the ’80s when Ada was hyped as the language of the future before it dropped off the radar. I dismissed it as just another DoD project destined to go nowhere. After digging into it now, I’m shocked to find it’s alive and well—and often outperforms C/C++! It may not have the vast libraries and hardware support of C or C++, but with its compiler as a part of the GCC collection, it’s more than adequate for most embedded work.
It looks like it’ll be easy to pick up, too. It’s almost identical to Pascal. Strangely enough, Ada far more popular outside the U.S. despite its English keywords—especially in France of all places. As a Canadian, I figure Ada must be exceptionally good if it can get French speakers to tolerate anything remotely anglophonic.
I’m going to buy a book and spend my evenings learning Ada. C and C++ is a huge mess and Rust is pure psychobabble. I really hope Ada doesn’t disappoint me.
Thanks for pointing out Ada!
9
u/kammce Jan 10 '26
I do teach this in my embedded C++ course but I've found in the past that the codegen is not good. It's readable but each bit change performs a read-update-write. This makes sense since the register object or its members will usually be labelled volatile and each modification is assumed to have a side effect and thus the compiler must emit each individual bit change as a read-update-write. This also results in code bloat from the additonal bit operations. This may seem pedantic but much of my career has been around code size efficiency, and the small things count.
Whereas my C++ bit manipulation library takes a reference to a volatile integral, performs a read, and you can perform multiple operations on the bits, then on destruction or call to update() the bits are writen back to the register. The temp value isn't volatile, so the compiler can combine operations, improving performance and code size.
Here's an example from my unit tests:
constexpr auto enable_bit = bit_mask::from(1);
constexpr auto high_power_mode = bit_mask::from(15);
constexpr auto clock_divider = bit_mask::from(20, 23);
constexpr auto phase_delay = bit_mask::from(24, 27);
constexpr auto single_bit_mask = bit_mask::from(1);
// Exercise
bit_modify(control_register)
.set<enable_bit>()
.clear<high_power_mode>()
.insert<clock_divider>(0xAU)
.insert<phase_delay, 0x3U>();At some point I plan to write a SVD generator to write my masks. Hopefully C++29 reflections will be powerful enough to perform object generation so I can stuff my masks under the name of a struct.
2
u/slow-quark Jan 10 '26
You can take a look at https://github.com/nicocvn/cppreg.
Relatively easy to generate headers from a SVD file with Python (cmsis-svd package).
24
Jan 10 '26
If you’ve worked really low level, this pattern feels obvious. If you’ve worked on portable C, it feels dangerous. Both are correct in their domains.
24
u/tiajuanat Jan 10 '26
Bit fields are great, except it's compiler and processor dependent on whether it's lsb or msb order. Using shifts is more reliable even though less ergonomic.
2
u/dudesweetman Jan 10 '26
Most stuff these days are LSB. Sure MSB happens but in those rare cases then you are painfully aware of it.
11
u/tiajuanat Jan 10 '26
I've run into systems that are Most Significant Byte but still Least Significant Bit, and it drove me up a gd wall. That's why I don't rely on bitfields.
8
8
u/CompuSAR Jan 10 '26
Just keep in mind that the standard does not dictate how the bits map to the byte. This means that different compilers might make this mapping differently.
35
u/almost_useless Jan 10 '26
Based on the screenshot I'm guessing the trick is to write redundant comments...
9
u/mustbeset Jan 10 '26
The really needed comment is missing "Source: ABC123 datasheet, revision X, table 42.21, docid: 1231234"
We are lazy. We don't write something twice. We don't want to read same thing twice. Only if something is special or unexpected we add a note, i. e. "CAUTION: If testmode is activated while debug mode is active, device will be bricked. Only activate test mode if device was idle before."
5
14
u/Revolutionary-Poet-5 Jan 10 '26
This is generally to be avoided due to portability issues especially when accessing IOMMU. It looks nice but bitmasks using shifts are the way to go.
6
u/ObligationSorry9463 Jan 10 '26 edited Jan 10 '26
With the latest C Standard you can check (static_assert) the compiler capability during compile time.
10
u/Revolutionary-Poet-5 Jan 10 '26
It has nothing to do with compiler capability. Bit order in bitfields is not guaranteed by C standard and this is why it's not used for portable IOMMU which can run in different endianness systems. Check Linux kernel code for example. Of course as long as it's not mapped to some hardware registers it's perfectly fine to use.
4
6
12
u/mcergun Jan 10 '26
This f*s up when the registers are flushed on read or endianness is not matched between the register and CPU.
Though it feels good to use.
1
4
u/dmitrygr Jan 10 '26
be careful if using non-gcc compilers. bit order is not promised. gcc is unlikely to change how they allocate bit order (but they could). other compilers might do something else.
worse yet, if you do this for a hardware register, access size is not promised. if your reg is a u32 the compiler is free to load it only as a byte if you only asked for a bit. or to store to it as a byte store.
for many IPs out there such an access would be illegal and could cause issues, fault, or be ignored.
1
u/rsaxvc Jan 12 '26
Gcc uses both bitfield orders, though they always seem to follow the byte endianness. I went looking for mismatches recently but couldn't find any.
2
3
u/Echelon_X-Ray Jan 10 '26
Yep. It's useful for a variety of things. Not a very well known feature.
Correct me if I'm wrong, but I'm pretty sure that in pure C, it is also legal to type pun through a union. I've used this to access the Floating Point components of the mantissa, exponent, and sign bit as integers by punning it through a union. I've also used it in an emulator to decode CPU instructions, though I later changed to different solution.
This solution does tend to fall down when things are not so neatly aligned into larger 16 or 32 bit types. For example: when I was writing a FLAC stream decoder, I ended up writing a neat little helper function to read-in bits instead.
3
u/NE558 Jan 10 '26
I just stay away from it since such constructions might not work on other machine / compiler in same way (misplaced bitfields) or after compiler update. IIRC it will also truncate written values silently which is in my opinion very bad.
I preffer to use overloaded helper functions like SetPartOfReg/GetPartOfReg in business logic. Not super optimal in code execution since computation is done, not super user-friendly since you need to write lots of things: value/register you want to modify/access, value, bitfield size and offset, but It can also catch potential bugs like trying to write too big value (no truncation allowed in my implementation)
Note: I am not great at C/C++. I also don't do time critical stuff (mostly). I accept my strategy is not optimal. I prefer being strict as much as possible to avoid bugs (which bitfields can cause)
3
u/Spirited-Guidance-91 Jan 11 '26
__attribute__((packed)) is a GCC/clang extension
On some architectures there's efficient bit-packing/unpacking instructions (like ARMv7-m's UBFX/BFI/BFC) that you can use to manipulate multiple bitfields at once that ought to be used instead.
Using bitfields also usually implies a RMW cycle that is hidden from you. This can have odd consequences if you need bitfield changes to happen "atomically".
3
u/DiscountDog Jan 11 '26
Unions are handy - and problematic with respect to endian-ness.
Bit-fields - used here - are just a big flashing "KICK ME" sticker, as they are totally dependent on the implementation of the compiler.
Be very, very careful using these tricks. I thought I was clever 35 years ago doing so and, suffice it to say, wasn't.
3
u/reini_urban Jan 11 '26
__attribute__((packed))is not needed and only compiles on gcc, clang. The types must be unsigned, not uint8_t.
We use bitfields for 30 years on all compilers. Perl5 core eg
4
u/cybekRT Jan 10 '26
What trick, wasting the one bit, because you used 3 separate bits for brightness instead of using 2 bit field as brightness level!?
2
u/H1BNOT4ME Jan 11 '26
That's not his problem. It's representing hardware and he has no control over its implemention.
1
u/cybekRT Jan 11 '26
What hardware? It looks like pure example to show usage of bit fields. At first I was joking, but to be honest, if you want to teach something, show proper use, especially since this shows only one-bit fields, not multi-bits fields.
1
u/hey-im-root Jan 13 '26
It’s for simplicity, yes you can make brightness multiple bits but you’d have to change the implementation
2
u/_gipi_ Jan 10 '26
It's not clear what you are talking about, union is built into the language or you assume by magic the language can split 8bits in single elements with names? or are you talking about packed?
Moreover, I hope that someone working more than ten minutes in embedded can learn this trick (whatever thing you are talking about anyway) reading source code from any driver in the wild.
2
u/UnHelpful-Ad Jan 10 '26
And you can do a silent strict. So no need to name it s if you needed it ;)
2
u/EkriirkE Bare Metal Jan 10 '26
Why allow multiple brightnesses, you can consolidate 4 of those bits into 2 as use them as a "real" int
2
u/koffiezet Jan 10 '26
I'm familiar, but I've had to port too much embedded C code to various random platforms when I was younger to ever actually use this.
2
2
2
2
u/EmbedSoftwareEng Jan 12 '26
You can ditch the struct name (s), and just use an anonymous struct.
I do this with a typedef as well, where I call the primitive member "raw" instead of "hw". You can do things like
example_reg_t example = example_get(PERIPHERAL_HARDWARE_POINTER);
if (example.raw)
{
// Do something if any flags set
if (example.IDLE)
{
// Do only Idle things.
}
if (example.PARTY_MODE)
{
// Let's party!
}
// etc.
}3
u/No_Annual_7630 Jan 10 '26
this is breaking just about any/every defensive programming tenets.
datatype ambiguity.
Target Architecture portability.
Cross Compiler compatibility.
This is great if you're just working on one microcontroller for the last 30 years. But, post covid every embedded s/m product companies are weary about overdependence on one model of micro.
3
u/AssemblerGuy Jan 10 '26
Any static analyzer worth its salt will throw a hissy fit at this.
You really don't want to do this. The subtle difference between C and C++ alone will cause incurable headaches. C++ has a concept of "lifetime", C doesn't, and undefined behavior lurks just around the corner.
4
u/krudef Jan 10 '26
Absolutely. It’s a crucial skill I find myself teaching junior developers time and again, usually alongside the ternary operator
2
1
u/Cyclophosphamide_ Jan 10 '26
This was mentioned in Sam’s teach yourself c in 21 days book. You don’t need the attribute((packed)) part right? From what i read you could do it with any struct.
4
u/nekokattt Jan 10 '26 edited Jan 10 '26
does the use of bitfields ensure no alignment?
I always assumed it was at most a hint to the compiler that it could choose to pack.
3
u/foo1138 Jan 10 '26
packed has nothing to do with the bitfields. packed loosens the BYTE-alignment -- not the BIT-alignment. You can remove the packed attribute and it would work the same, because everything is uint8_t and all the bits fit into one byte, the struct is just one byte in size anyway.
1
u/Grumpy_Frogy Jan 10 '26
Some 6 years ago or something, in university one of the project was to program a part of an audio player (used pic16f887), IR receiver, audio control (2 rotary encoders or lcd screen. I used this exact trick union struct trick to decode IR signal, as I first bit shifted IR output into a buffer then checked the simply checked bit field based on there position in the struct to handle what the signal encode e.g. volume up/down or change input channel.
1
1
1
1
u/rsmith9945 Jan 11 '26
I do this all the time! It’s great for bit packing
1
u/rsmith9945 Jan 11 '26
If you want it bit packed, you need to add the align argument:
struct __attribute__((packed, aligned(1)))
1
1
u/OverclockedChip Jan 11 '26
How does this work? EXAMPLE_REGISTER can be accessed as an uint8 (EXAMPLE_REGISTER.hw) or as as individual bit field (.s)?
Is the declaration usually marked volatile?
1
Jan 11 '26
TI's C2000 controllers has the same way( or similar) of programming which are known as bitfields. To be honest this method is amazing, it's just makes accesing registers easier and makes the code readable (both as developers' and readers' perspective)
1
u/--Fusion-- Jan 11 '26
It's a neat one that is appropriate about 5% of the time you'd initially think due to all the associated caveats. Still, a very good tool.
1
u/Turbulent_File3904 Jan 11 '26
nah, bit field size and order are implementation defined, so it technically 1 bit bitfiled can take 1 byte. dont do that just use bit mask and bitshift.
unless you want to lockin specific compiler oc
1
u/zydeco100 Jan 11 '26
I'd rather use an enumerated value for a state machine and avoid the possibility of this variable having multiple values. This is how you get those wierd bugs that take days to solve because any code that logically ANDs the variable says "I don't see a problem".
1
1
u/IosevkaNF Jan 11 '26
The reason not every C curriculum teaches is that because this is un portable, endiannes non-respecting, heavily implementation dependent code that would not have this problem if they just used a docstring and some defines / functions. I hope you understand how oxymoronic this code is. Using an uint8 for one bit? Yeah lemme just put 8 bits of info into one!
1
u/KKoovalsky Jan 11 '26
I created a C++ library that solves the problem of compiler specific endianness and packing: https://github.com/KKoovalsky/PortableBitfields
1
u/namotous Jan 11 '26
It’s not an issue here as it’s a byte, but if you start going higher in size, ie. 16/32 bits, the order of the bitfields matter whether you’re using little or big endian. Believe it or not, some project still use powerpc mcu. I spent an entire day debugging this issue, we tried to port a project onto another platform, which is running big endian
1
u/bless-you-mlud Jan 11 '26
I like to quote K&R on bit-fields: "Almost everything about fields is implementation-dependent." Not exactly a glowing recommendation.
1
u/niepiekm Jan 11 '26
Have you heard about Duff’s Device? http://doc.cat-v.org/bell_labs/duffs_device
1
u/niepiekm Jan 11 '26
For elegant register access in C++ see this https://yogiken.wordpress.com/wp-content/uploads/2010/02/c-register-access.pdf and that for more https://www.youtube.com/watch?v=lrrQaa_-hzU
1
u/mfuzzey Jan 11 '26
I wouldn't use this method for accessing hardware registers that have to have defined bit positions (as seems to be the intention here) as the compiler is free to order the bits as it sees fit.
On the other hand it's fine for software only state that doesn't need to match hardware or be persisted and read with a version of the code compiled with a different compiler
1
u/lenzo1337 Jan 11 '26
NGL I do this with packed structures and bitfields semi-often when I'm working with eeprom or small storage.
But for larger systems I have my own register editing library that is heavily tested and has it's own mock implementation to allow host testing and safe bit twiddling.
Gotta love C
1
u/the-_Ghost Jan 12 '26
Standard macros ((1u << 2)) are ugly, but at least they are deterministic. With bitfields, you are at the mercy of the compiler's specific ABI and padding rules (even with __packed). Great for internal state flags.
1
u/kaddkaka Jan 14 '26
This makes me hope even more for new modern languages like zig.
Bitfield The fields of a packed struct are always laid out in memory in the order they are written, with no padding, so they are very nice to represent a bitfield.
Boolean values are represented as 1 bit in a packed struct, Zig also has arbitrary bit-width integers, like u28, u1 and so on.
const std = @import("std");
const print = std.debug.print;
const ColorFlags = packed struct(u32) {
red: bool = false,
green: bool = false,
blue: bool = false,
_padding: u29 = 0,
};1
u/vbpoweredwindmill Jan 15 '26
Question: why can't you write an array of 8 bools for 1 byte?
I don't mean that to invalidate what you've done, I mean it as "why isn't this an answer to this problem?"
1
u/affenhirn1 Jan 10 '26
is the packed attribute necessary in this particular example?
2
u/foo1138 Jan 10 '26
No, packed is not necessary in this situation. It is even bad, because it is compiler specific.
1
u/fanofreddithello Jan 10 '26
So the eight uint8's are combined into ONE byte? Do I get this right? Automatically?
4
1
u/RumbuncTheRadiant Jan 11 '26
Attribute packed is non standard and can be put in the wrong place (One major package I know of did... and just silently did the wrong thing but "worked by accident" on the CPU they developed on).
I have being enjoying working with this instead...
0
u/Circuit_Guy Jan 10 '26
Serious question: Does this sort of low level optimization translate to Rust? I'm always wondering if I'm about to fall behind the curve by not taking it seriously for embedded work.
8
u/ProfessorDonuts Jan 10 '26 edited Jan 10 '26
It isnt necessarily a optimization, just a clean way to refer to a single memory mapped hardware register, it lets you access the same 8-bit value either by the entire value or by its corresponding bit fields (it handles the mask calculations for you).
So you can do something like
reg.s.DEBUG_MODE = 1;rather than
#define DEBUG_BIT_MASK 0x20 reg |= 0x20; or reg |= DEBUG_BIT_MASK;The bitfield approach will calculate the masks (0x20) for you. At the end of the day it still a read-modify-write operation with clean bitmask handling (seen here: https://godbolt.org/z/PK5rcbarE).
In C++ you can write some template based memory-mapped register abstractions. Abstractions that allow you to enforce RO/RW/WO, atomic bit set, safety checks, similar clean bitfield handling, etc. As mentioned, these are not optimizations but rather code cleanliness, but in this case also provides safety/sanity checks. However one could argue that adding atomic bit sets to the mmio abstraction in C++ is a performance optimmization.
In Rust, HAL's that follow the PAC model will expose three methods for manipulating mmio registers:
read(),modify(),write(). Methods likewrite()are provided as closures, so using the example register definition in this post, if i wanted to set the IDLE and DEBUG_MODE bit in the register, it would be written in rust as:example_reg.write(|r| r.idle.set_bit().debug_mode.set_bit())In this example, we write to the mmio register
example_regusingwrite, representing it the closure as "r", and set the idle and debug_mode bit in the register. Its not as visually appealing as the C/C++ bitfields but it provides the same named-bitfield access functionality in addition to security.1
u/ihatemovingparts Jan 11 '26
Rust
Has unions that put a few more guardrails in place, but they're still a bad idea for something that might run on a different architecture.
PACs typically abstract the bit fields for registers away with const accessors and for more general use folks typically use the bitfield and/or bitflag crates as appropriate.
-3
u/DeathDonkey387 Jan 10 '26
Assuming the "trick" is the union bitfield struct, this is an utterly pointless example as the entire thing should be an enum instead.
0
0
u/Different-Ad-8707 Jan 12 '26
This looks like a shoddy implementation of distinguished unions. Like Enums is Rust but more hacky. Is this stuff like, C compiler standardised or undefined behavior?
-6
u/mrheosuper Jan 10 '26
Nah not a fan of this. This is for what, saving a few byte ? Can you do atomic operation on it ? And what about extendability. What if DEBUG_MODE is not simply on/off anymore, but a level(EXTENDED, LOG_ONLY, DISABLE) ?
It's great for back in the day when mcu has like less than 1kb of ram.
177
u/emrainey Jan 10 '26
Yes! Many do not! They have been convinced that unions are too platform specific or UB that they don't pursue using this.
I made a project to covert SVD files to this format
https://github.com/emrainey/peripheralyzer