Note that there are some explanatory texts on larger screens.

plurals
  1. POEfficiency of data structures in C99 (possibly affected by endianness)
    primarykey
    data
    text
    <p>I have a couple of questions that are all inter-related. Basically, in the algorithm I am implementing a word <code>w</code> is defined as four bytes, so it can be contained whole in a <code>uint32_t</code>. </p> <p>However, during the operation of the algorithm I often need to access the various parts of the word. Now, I can do this in two ways:</p> <pre><code>uint32_t w = 0x11223344; uint8_t a = (w &amp; 0xff000000) &gt;&gt; 24; uint8_t b = (w &amp; 0x00ff0000) &gt;&gt; 16; uint8_t b = (w &amp; 0x0000ff00) &gt;&gt; 8; uint8_t d = (w &amp; 0x000000ff); </code></pre> <p>However, part of me thinks that isn't particularly efficient. I thought a better way would be to use union representation like so:</p> <pre><code>typedef union { struct { uint8_t d; uint8_t c; uint8_t b; uint8_t a; }; uint32_t n; } word32; </code></pre> <p>Using this method I can assign <code>word32 w = 0x11223344;</code> then I can access the various parts as I require (<code>w.a=11</code> in little endian).</p> <p>However, at this stage I come up against endianness issues, namely, in big endian systems my struct is defined incorrectly so I need to re-order the word prior to it being passed in.</p> <p>This I can do without too much difficulty. My question is, then, is the first part (various bitwise ands and shifts) efficient compared to the implementation using a union? Is there any difference between the two generally? Which way should I go on a modern, x86_64 processor? Is endianness just a red herring here?</p> <p>I could inspect the assembly output of course, but my knowledge of compilers is not brilliant. I would have thought a union would be more efficient as it would essentially convert to memory offsets, like so:</p> <pre><code>mov eax, [r9+8] </code></pre> <p>Would a compiler realise that is what happening in the bit-shift case above?</p> <p>If it matters, I'm using C99, specifically my compiler is clang (llvm).</p> <p>Thanks in advance.</p>
    singulars
    1. This table or related slice is empty.
    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.
    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