Unix C ++ bitfield task

Can someone find out me why I should use union and for what purpose the same address for the cin'ed variable and bit of the field (task from the Shields book C ++)? In other words, why should I use union for:

char ch; bit of string byte;

// Display the ASCII code in binary format for characters.

#include <iostream> #include <conio.h> using namespace std; // a bit field that will be decoded struct byte { unsigned a : 1; unsigned b : 1; unsigned c : 1; unsigned d : 1; unsigned e : 1; unsigned f : 1; unsigned g : 1; unsigned h : 1; }; union bits { char ch; struct byte bit; } ascii ; void disp_bits(bits b); int main() { do { cin >> ascii.ch; cout << ": "; disp_bits(ascii); } while(ascii.ch!='q'); // quit if q typed return 0; } // Display the bit pattern for each character. void disp_bits(bits b) { if(b.bit.h) cout << "1 "; else cout << "0 "; if(b.bit.g) cout << "1 "; else cout << "0 "; if(b.bit.f) cout << "1 "; else cout << "0 "; if(b.bit.e) cout << "1 "; else cout << "0 "; if(b.bit.d) cout << "1 "; else cout << "0 "; if(b.bit.c) cout << "1 "; else cout << "0 "; if(b.bit.b) cout << "1 "; else cout << "0 "; if(b.bit.a) cout << "1 "; else cout << "0 "; cout << "\n"; } 
+4
source share
4 answers

As a union, both ch and bit have an overlapping (common) memory location. Store the character in it as ch , and then reading bit gives the corresponding bit values ​​for the character.

+4
source

The real answer is you would not do that. Using bit fields in unions (or in general) like this is inherently unsportsmanlike and can be undefined. If you need to fiddle with bits, you are much better off using C ++ bitwise operators.

+4
source

Because the exercise demonstrates breaking a value into bits using a bit field and a union.

Assuming you know what a join is, if you are extracting something less repetitive from a binary value, then you can use it for clarity instead of saying two 24-bit 48-character integers from shifts and masks.

But for an example in a task, shifts and masks would be cleaner code, so you probably would not use union for this task.

 void disp_bits(unsigned b) { // not tested for ( int shift = 7; shift >= 0; --shift ) cout << ( ( b >> shift ) & 1 ) << ' '; cout << "\n"; } 
+1
source

Unions are used in network protocols. They can also be useful for faking polymorphism in C. Usually they are a special precedent.

In this example, this is a kind of dummy example showing you a little code.

-5
source

Source: https://habr.com/ru/post/1313122/


All Articles