We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you a podcast all about Citrix Workspace, moving to the cloud, and analytics & intelligence. Episode 2 coming soon!Listen Now

x

# Duplicating binary data in array

on
Medium Priority
244 Views
Hi,
I have an array of unsigned longs called "lookup". I need to copy a bit from one part of the "marix" to another.
i.e. at the jth bit from the right in row[i] should equal the xth bit from the right in row[y].

I'm trying to do this with bitwise operators. I've come up with somthing like:

lookup[i] |= (lookup[y] & (1L << x)) >> (j-31)

(Don't worry, there arn't any magic numbers in the actual program!)
For instance, when i = 2, j=29, y=1, x=30:
Start:
lookup[0] = 0 0 0 0 0 0 0 0 0 ... 0
lookup[1] = 0 1 0 0 0 0 0 0 0 ... 0
lookup[2] = 0 0 0 0 0 0 0 0 0 ... 0
Should finish up like:
lookup[0] = 0 0 0 0 0 0 0 0 0 ... 0
lookup[1] = 0 1 0 0 0 0 0 0 0 ... 0
lookup[2] = 0 0 1 0 0 0 0 0 0 ... 0

Any help would be really appreciated.

Chris
Comment
Watch Question

## View Solution Only

CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015
Commented:
lookup[i] |= ((lookup[y]>>x) & 1) << j;

Not the solution you were looking for? Getting a personalized solution is easy.

CERTIFIED EXPERT
Top Expert 2006

Commented:
> at the jth bit from the right in row[i] should equal the xth bit from the right in row[y].

row[i] = row[i] & (~(1<<j));     //clear off the target bit

sourcebit = !(!(row[y] & (1<<x))); //get if the bit at source is 0 or 1

row[i] = row[i] | (sourcebit<<j);   //set the bit

Ofcourse it is possible to shrink all of this in one line, but it is much more readable this way.
CERTIFIED EXPERT
Top Expert 2006

Commented:
Problem with not clearing target bit before ORing is that if previous value of this bit was 1 and new value was 0, results will be incorrect.

Commented:
Thanks everybody! Ozo got it first with the best answer so he gets the points. (Sorry sunnycoder! I don't check my email often enough). Thanks heaps.
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

Commented:
lookup[i] ^= (((lookup[y]>>x ^ lookup[i]>>j) & 1) << j);
##### Thanks for using Experts Exchange.

• View three pieces of content (articles, solutions, posts, and videos)
• Ask the experts questions (counted toward content limit)
• Customize your dashboard and profile