1

I have a big numpy array (i.e. approx. 2 ** 32 positions) of 64-bit unsigned integers and I want to duplicate a single bit (can vary from 0 to 63) in every integer inside this array.


Example:

  • Input array: array([ 0, 5, 2, 7 ])
  • Position (right to left) to duplicate: 0

The input, in binary, is

000  101  010  111

After the operation, I want the bits as

0000 1011 0100 1111
  • Result: array([ 0, 11, 4, 15 ])

As stated, my arrays are huge, so I'd prefer to use the lowest number of temporary / auxiliar arrays.

I tried to find something close to it in Google or even Bit Twiddling Hacks with no luck.

Thanks in advance!

6
  • This is far too straightforward to end up in the bit twiddling hacks list: (x << 1) | (x & 1). Commented Apr 12, 2017 at 19:55
  • 1
    @user2357112 this only works when position = 0. Any bit can be duplicated. Commented Apr 12, 2017 at 19:56
  • Do you want to duplicate the same bit position in every integer? Or will the bit you want to duplicate vary? Commented Apr 12, 2017 at 20:05
  • @sgrg It's the same position in every integer Commented Apr 12, 2017 at 20:06
  • Still too straightforward: part1 = x & -(1 << pos); part2 = x & ((1 << (pos+1))-1); return (part1 << 1) | part2;. Select two pieces of the integer overlapping at the duplicated bit, and paste those pieces together without overlapping. Commented Apr 12, 2017 at 20:07

1 Answer 1

1

Implementation

The naive way already seems pretty efficient to me:

mask = -1 << (pos + 1)
(x << 1) & mask | x & ~mask

Benchmark

I ran the code as follows:

import numpy as np
import time

array = np.arange(2 ** 27, dtype=np.uint64)
pos = 5

t = time.process_time()
mask = np.uint64(-1 << (pos + 1))
array = (array << 1) & mask | array & ~mask
print(time.process_time() - t)

The bit duplication took 0.95 seconds (average of several runs). Due to memory issues, I used only 227 entries. But we can expect the time for 232 entries to be 232-27 × 0.95 s = 25 × 0.95 s = 32 × 0.96 s = 30.4 s.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.