Note that there are some explanatory texts on larger screens.

plurals
  1. POCalculating parity bit with the preprocessor (parity functional style with call by ref)
    primarykey
    data
    text
    <p>Consider I want to generate parities at compile time. The parity calculation is given literal constants and with any decent optimizer it will boil down to a single constant itself. Now look at the following parity calculation with the <strong>C</strong> preprocessor:</p> <pre><code>#define PARITY16(u16) (PARITY8((u16)&amp;0xff) ^ PARITY8((u16)&gt;&gt;8)) #define PARITY8(u8) (PARITY4((u8)&amp;0x0f) ^ PARITY4((u8)&gt;&gt;4)) #define PARITY4(u4) (PARITY2((u4)&amp;0x03) ^ PARITY2((u4)&gt;&gt;2)) #define PARITY2(u2) (PARITY1((u2)&amp;0x01) ^ PARITY1((u2)&gt;&gt;1)) #define PARITY1(u1) (u1) int message[] = { 0x1234, 0x5678, PARITY16(0x1234^0x5678)); </code></pre> <p>This will calculate the parity at compile time, but it will produce an enormous amount of intermediate code, expanding to 16 instances of the expression <code>u16</code> which itself can be e.g. an arbitrary complex expression. The problem is that the <strong>C</strong> preprocessor can't evaluate intermediary expressions and in the general case only expands text (you can force it to do integer arithmetic in-situ but only for trivial cases, or with gigabytes of #defines). I have found that the parity for 3 bits can be generated at once by an arithmetic expression: <code>([0..7]*3+1)/4</code>. This reduces the 16-bit parity to the following macro:</p> <pre><code>#define PARITY16(u16) ((4 &amp; ((((u16)&amp;7)*3+1) ^ \ ((((u16)&gt;&gt;3)&amp;7)*3+1) ^ \ ((((u16)&gt;&gt;6)&amp;7)*3+1) ^ \ ((((u16)&gt;&gt;9)&amp;7)*3+1) ^ \ ((((u16)&gt;&gt;12)&amp;7)*3+1) ^ \ ((((u16)&gt;&gt;15)&amp;1)*3+1))) &gt;&gt; 2)) </code></pre> <p>which expands <code>u16</code>only 6 times. Is there an even cheaper (in terms of number of expansions) way, e.g. a direct formula for a 4,5,etc. bit parity? I couldn't find a solution for a linear expression of the form <code>(x*k+d)/m</code> for acceptable (non-overflowing) values k,d,m for a range > 3 bits. Anyone out there with a more clever shortcut for preprocessor parity calculation?</p>
    singulars
    1. This table or related slice is empty.
    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