Ad

Friday, 14 June 2013

Algo#14: Set specified bits range in number.

Set specified bits range in number.

Following is simple algorithm for setting bits range in given number.
Step 1: Make mask for start index to end index.
        1.1: First step to make mask is, set 1 in each position from 0 to end index, call it mask-1.
        1.2: Then same way, set 1 in each position from 0 to start index, call  it mask-2.
        1.3: XOR mask-1 and mask-2, which will give us our desired mask having 1 set from start to end index.
Step 2: Do OR operation between given number and mask.

Following is implementation of above algorithm in c language in 1 line.





Please write comments if you find anything wrong or you want to add something more related to this topic.

No comments:

Post a Comment

Write your comment here.

Ad