algorithmlanguage-agnosticbit-manipulationbitfoo

Setting last N bits in an array


I'm sure this is fairly simple, however I have a major mental block on it, so I need a little help here!

I have an array of 5 integers, the array is already filled with some data. I want to set the last N bits of the array to be random noise.

[int][int][int][int][int]

eg. set last 40 bits

[unchanged][unchanged][unchanged][24 bits of old data followed 8 bits of randomness][all random]

This is largely language agnostic, but I'm working in C# so bonus points for answers in C#


Solution

  • Without any bit-fu in C#:

    BitArray ba = new BitArray (originalIntArray);
    for (int i = startToReplaceFrom; i < endToReplaceTo; i++)
        ba.Set (i, randomValue);