0

I am working with C and C++ for some time.

While learning the basics you can bump into such interesting thing as bit fields. Usage of bit fields in programming practice has somehow controversial character.

In which kind of situations this low-level feature usage provides a real benefit, and are there concrete examples of using bit fields properly?

Ilya Tereschuk
  • 1,204
  • 1
  • 9
  • 21
  • 1
    Try writing a variable sized columnar database. – Elliott Frisch Jan 03 '14 at 19:41
  • 1
    This is a bit broad. But low-level serialization in a platform dependent way can benefit from bit fields, as can large in-memory data structures, cache-friendly memory-bound work, etc. – Yakk - Adam Nevraumont Jan 03 '14 at 19:42
  • @Yakk They can't really be used for serialization, because there is so much that is unspecified with regards to how they are laid out. – James Kanze Jan 03 '14 at 19:45
  • 2
    @JamesKanze The phrase "in a platform dependent way" is important: Unspecified layout by the standard does not mean unspecified by your compiler, and many compilers do lay them out in a nicely packed way and are stable between iterations of the compiler. – Yakk - Adam Nevraumont Jan 03 '14 at 19:46
  • They can be used in embedded processors for bit-packing communication protocols, packing data, mapping to register flags. This relys on knowing how the compiler packs, so it's specific to a given compiler/processor combination. But that's completely acceptable when you are writing for very specific embedded hardware. – AShelly Jan 03 '14 at 19:47
  • 1
    @Yakk Some compilers (I suppose) do document this, but that does tie you to a particular compiler. And most compilers don't. (I've not found such documentation in any of the compilers I've used.) – James Kanze Jan 03 '14 at 19:48
  • I've edited question, please reopen, don't let it die – Ilya Tereschuk Jan 03 '14 at 19:50
  • @ElliotTereschuk - this edit won't likely merit a reopen. But consider this - you have a LOT of object with properties that can be expressed in few bits, this is a perfect scenario to use bitfields. For example, 8 bool properties will take 8 bytes if stored in a `bool`, but with bitfields they will take only 1 byte. – dtech Jan 03 '14 at 19:55
  • 2
    @JamesKanze: The ISO/IEC C standard *requires* such implementation details to be documented. For example see [ARM's documentation](http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0472j/chr1360775115791.html). If your compiler does not document this, then it cannot truly be said to be ISO compliant. – Clifford Jan 03 '14 at 19:57
  • @ElliotTereschuk It is still a survey question. SO aims to answer *specific* problems for which there is a *solution*. The question as written would have many answers. It is interesting, but SO's current standards say "not a question to ask here". – Yakk - Adam Nevraumont Jan 03 '14 at 20:03

4 Answers4

2

When working with embedded systems and microcontrollers, individual bits in a register may be associated with a processor setting or input/output. Using bit fields allows these individual bits to be worked with by name instead of doing bitwise operations on the entire register.

It's mostly an aesthetic feature but can increase code readability in some applications.

  • Except that they don't work for this, unless your compiler specifies otherwise. (Which, of course, binds you to one particular compiler. But most embedded systems will be more or less bound to a particular compiler anyway.) – James Kanze Jan 03 '14 at 19:46
1

There's probably not much use for bit fields on a modern, high performance machine, but for smaller machines, they can be very useful to save memory, if you have large arrays of the structures. Other than saving memory, however, there's no use for them.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • It is not only about saving memory (in fact that is probably amongst the least common uses). Register bitfield mapping for SoCs and microcontrollers is more likely. For example [this PIC16 header](http://www.ecse.rpi.edu/courses/CStudio/SDCC%20Compiler/sdcc-src-2.8.0/sdcc-src-2.8.0/sdcc/device/include/pic/pic16f690.h) makes extensive use of bitfields, as do part specific headers for most microcontrollers and SoCs. – Clifford Jan 03 '14 at 20:10
  • Inline assembly is still common on modern CPUs. MATLAB, for example, makes extensive use of platform-specific optimizations. Some code involves explicitly setting specific registers. – Cloud Jan 03 '14 at 20:35
1

There are several use cases for bit fields, even on modern machines.

The first would be when you are handling register level logic. This is common when you are setting modes and how certain pieces of hardware work. This is even more common on embedded devices. On Arduino devices, for example, the "PinMode" logic is basically setting individual bits high or low to indicate whether a digital I/O pin is in "input" or "output" mode.

http://arduino.cc/en/Reference/pinMode

Secondly, when writing optimized, in-line assembly code in a C/C++ program. There are times where you want to take advantage of hardware-optimized instructions to speed up your program's execution as much as possible:

http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html

A final common example is when writing packet drivers or implementing specific protocols. I recently just posted a question on this, where it turns out I was using a 32-bit variable instead of an 8-bit variable composed of bitfields, which was causing my code to break:

Basic NTP Client in Windows in Visual C++

So, in short: when talking directly to hardware, or in networking code.

Community
  • 1
  • 1
Cloud
  • 18,753
  • 15
  • 79
  • 153
1

In addition to the other answers, in some scenarios, using bit fields can improve both memory usage and performance.

Save memory by packing together properties which need few bits to express the range of possible values. Why put 8 bool properties as 8 bool members, when a single byte gives to the ability to store 8 boolean values in each bit - instead of 8 bytes you use only 1, 7 bytes saved is quite significant. Naturally, you would typically use a 32, 64 bit or wider bitfields. I have a similar scenario with a lots of objects with lots of properties which can be expressed in one or few bits, and for cases with high object count (millions) the memory savings are indeed significant.

Increase performance - although bitfields come with a small performance penalty (to access the actual value with shifting and masking) those operations are really fast. Packing more data and wasting less bits can give you better cache efficiency, which can result in performance gain that is greater than the bit fields access penalty. Not only it may be faster to access individual bits than fetching another line from the cache and more probable to find the data in the cache if it is packed, but this will pollute the cache less, leaving more available space for other processes.

dtech
  • 47,916
  • 17
  • 112
  • 190