Search code examples
c#.netsimdsystem.numerics

How can I count the occurrence of a byte in array using SIMD?


Given the following input bytes:

var vBytes = new Vector<byte>(new byte[] {72, 101, 55, 08, 108, 111, 55, 87, 111, 114, 108, 55, 100, 55, 55, 20});

And the given mask:

var mask = new Vector<byte>(55);

How can I find the count of byte 55 in the input array?

I have tried xoring the vBytes with the mask:

var xored = Vector.Xor(mask, vBytes);

which gives:

<127, 82, 0, 91, 91, 88, 0, 96, 88, 69, 91, 0, 83, 0, 0, 35>

But don't know how I can get the count from that.

For the sake of simplicity let's assume that the input byte length is always equal to the size of Vector<byte>.Count.


Solution

  • Thanks to Marc Gravell for his tip, the following works:

    var areEqual = Vector.Equals(vBytes, mask);
    var negation = Vector.Negate(areEqual);
    var count = Vector.Dot(negation, Vector<byte>.One);
    

    Marc has a blog post with more info on the subject.