Note that there are some explanatory texts on larger screens.

plurals
  1. POVerify if a binary array is a subset of another one in C
    primarykey
    data
    text
    <p>I need to verify if the bits in an array of bytes (i.e. chars) are a subset of another array of the same type: for example, 0001.0011 (19) is a subset of 0011.0011 (51), while 0000.1011 (11) is not.</p> <p>I started playing with bitwise operations, and almost solved it with a XOR/OR/XOR sequence:</p> <pre><code>int is_subset (char *set_a, char *set_b, int size) { /* The operation is performed with three bitwise operations, resulting in a * sequence of bits that will be equal to zero if set_a is a subset of * set_b. As a bonus, the positions where the sets differ will be * available in the resulting sequence, and thus the number of differing * positions can be obtained by counting the number of bits set (for exemple, * with __builtin_popcount in GCC). * * Exemple (TRUE): Exemple (FALSE): * ================ ================ * set_a 00010011 set_a 00001011 * set_b 00110011 set_b 00110011 * ---------------- ---------------- * XOR 00100000 XOR 00111000 * set_b 00110011 set_b 00110011 * ---------------- ---------------- * OR 00110011 OR 00111011 * set_b 00110011 set_b 00110011 * ---------------- ---------------- * XOR 00000000 XOR 00001000 */ int i; for (i = 0; i &lt; size; i++) if ( (((set_a[i] ^ set_b[i]) | set_b[i]) ^ set_b[i]) != 0) return FALSE; return TRUE; } </code></pre> <p>but it fails (always returning TRUE) if <code>set_a</code> is zero (0000.0000). I tried different strategies (such as Bloom filters), but probably due to my programming skills it was far from fast or at least elegant.</p> <p>Is there any standard, elegant way of doing this without exceptions?</p> <p>EDIT: to be clear, in this context "subset" means that all bits TRUE in the first array (set_a) are also TRUE in the second one (set_b). There might be other bits TRUE in the second array, but it does not matter if they are FALSE in first array.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload