liveBook · Manning

Set union

As explained in Modern C, Third Edition

Set union is the operation producing a set containing every element that belongs to either operand set.

Set union produces a set containing every element belonging to either operand set. For bit sets, C's | operator performs this operation bit by bit. section 5.7.2

Combining two bit sets

Let A = 240 represent {4, 5, 6, 7}, and B = 287 represent {0, 1, 2, 3, 4, 8}. Then A | B = 511 represents {0, 1, 2, 3, 4, 5, 6, 7, 8}. The shared element 4 appears once. section 5.7.2

Table 5.6 Effects of bitwise operators
Bit op Value Hex 𝑏15…𝑏8 𝑏7…𝑏0 Set op Set
V 65,535 0xFFFF 0b11111111’11111111 {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
A 240 0x00F0 0b00000000’11110000 {4, 5, 6, 7}
~A 65,295 0xFF0F 0b11111111’00001111 \(V \setminus A\) {0, 1, 2, 3, 8, 9, 10, 11, 12, 13, 14, 15}
-A 65,296 0xFF10 0b11111111’00010000 {4, 8, 9, 10, 11, 12, 13, 14, 15}
B 287 0x011F 0b00000001’00011111 {0, 1, 2, 3, 4, 8}
A|B 511 0x01FF 0b00000001’11111111 \(A \cup B\) {0, 1, 2, 3, 4, 5, 6, 7, 8}
A&B 16 0x0010 0b00000000’00010000 \(A \cap B\) 4
A^B 495 0x01EF 0b00000001’11101111 \(A \Delta B\) {0, 1, 2, 3, 5, 6, 7, 8}

Compare the binary values, hexadecimal forms, and set interpretations of union, intersection, complement, and symmetric difference. section 5.7.2

In C bit sets, union has these practical properties:

  • Treats each unsigned value as a subset of a fixed base set whose members correspond to set bits. section 5.7.2
  • Uses |= to update a bit set by adding the bits present in another operand. section 5.7.2
  • Supports flags: setting a power-of-two flag adds that member to the represented set. section 5.7.2

In union-find, Union merges the two partition sets containing selected elements; Find identifies the root representing a partition set. section 4.6

How Modern C, Third Edition covers it

How deep it goes
Explains the set interpretation of bits, computes a worked union, and distinguishes union from related bitwise operations.
Examples
Uses A = 240 and B = 287, a bitwise-operator table, and corvid flock flags.
What it assumes
Assumes familiarity with unsigned values and binary representation while defining their alternative interpretation as bit sets.
What you can do after
Apply it via C's | and |= operators to combine represented sets and add flags.
How it connects
Connects set union with bitwise OR, bit sets, set intersection, symmetric difference, flags, and union-find.

Also explained in

Compare how 4 books explain set union →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.