Setting the last N bits in an array

I'm sure this is pretty simple, however I have a big mental block, so I need a little help here!

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

[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 pretty much language agnostic, but I'm working in C # so bonus points for C # answers

+2


a source to share


4 answers


Without any bit fu in C #:



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

      

+3


a source


When you XOR any data with random data, the result is random, so you can do this:

Random random = new Random();
x[x.Length - 2] ^= random.Next(1 << 8);
x[x.Length - 1] = random.Next(1 << 16);
x[x.Length - 1] ^= random.Next(1 << 16) << 16;

      

For a general solution for any N, you can use a loop:



for (int i = 0; i < 40; ++i)
{
    x[x.Length - i / 32 - 1] ^= random.Next(2) << (i % 32);
}

      

Note that this causes randomly more time than necessary, but simple.

+1


a source


In pseudo-Python:

N        = 5   # array size
bits     = 40  # for instance
int_bits = 32  # bits in one integer

i = N
while bits > 0:
    value_bits  = min (bits, int_bits)
    bits       -= value_bits
    mask        = (1 << value_bits) - 1

    i -= 1
    array[i] ^= random () & mask

      

0


a source


Int32 is 4 bytes or 32 bits.
So you need the last int and 8 more bits.

int lastEightBitsMask = 0x000F + 1;
Random rand = new Random ();
arr [arr.Length - 1] = rand.Next ();
arr [arr.Length - 2] ^ = rand.Next (lastEightBitsMask);

Explanation:
The last element modification should be pretty self- explanatory - if you want the last 40 bits, the last 32 bits are included.
The remaining eight bit modification is bounded at the top at 0x000F + 1, since the rand.Next argument is an exclusive upper bound, the randoms generated will be nothing more. The rest of the bits of the number will remain unchanged since 1 ^ 0 == 1 and 0 ^ 0 == 0.

0


a source







All Articles