0

I came across an algorithm that uses a lot of XOR shift like so:

std::uint16_t a = ...
std::uint16_t b = a ^ ( a >> 4 )

I read XOR is used for all kind of good stuff, like finding parity, determining odd/even counts etc. So I'm wondering: Does this operation (on its own) have a certain meaning? Is it a common pattern? Or is it just unique to this algorithm?

No I'm not talking about THE xorshift pseudo-number algorithm.

SamVanDonut
  • 361
  • 2
  • 14
  • 3
    I don't believe this is a common pattern. Is there more context to be had? – 500 - Internal Server Error Jul 29 '20 at 14:48
  • 2
    Are you talking about `a ^ ( a >> 4 )`, or just `a >> 4 `? – cigien Jul 29 '20 at 14:49
  • The full thing. @cigien – SamVanDonut Jul 29 '20 at 14:59
  • 2
    I can't say I've seen that often. The only thing it's *guaranteed* to do is not modify the first 4 bits, but the rest of the bits depend on `a`. I'd say this is algorithm specific. – cigien Jul 29 '20 at 15:02
  • @SamVanDonut Can you mention the name of the algorithm? – brc-dd Jul 29 '20 at 15:11
  • It's for computing a Hilbert Curve https://github.com/adishavit/hilbert/blob/master/hilbert.c. Within the algorithm the xor-shift is used multiple times. – SamVanDonut Jul 29 '20 at 15:21
  • The original paper by Arthur Butz is available [here](http://www.cslab.ece.ntua.gr/twiki/pub/Collab/MultidimensionalIndexing/Alternative_Algorithm_for_Hilbert_s_Space_Filling_Curve.pdf). It is very maths-heavy, but explaining it – and that particular implementation – is not a good SO subject. – molbdnilo Jul 29 '20 at 15:45
  • All that bit-twiddling is there because there can be different numbers of axes with different numbers of bits per coordinate. (The code in your question does not occur in the code you linked to.) – molbdnilo Jul 29 '20 at 15:52

1 Answers1

2

Let's take a look at what it produces given input 0xIJKL:

  0xIJKL
^ 0x0IJK
--------
  0xI???

Doesn't seem very meaningful to me by itself, but this pattern seems to be used as a sub step in many parity bit twiddles. For example, a twiddle for calculating parity bit of a word (from https://graphics.stanford.edu/~seander/bithacks.html):

unsigned int v;  // word value to compute the parity of
v ^= v >> 16;
v ^= v >> 8;
v ^= v >> 4;
v &= 0xf;
return (0x6996 >> v) & 1;
eerorika
  • 232,697
  • 12
  • 197
  • 326