Showing posts with label Bit manipulations. Show all posts
Showing posts with label Bit manipulations. Show all posts

Friday, December 9, 2011

Write a function that adds two numbers. You should not use + or any arithmetic op- erators.

      int add_no_arithm(int a, int b) {
2            if (b == 0) return a;
3            int sum = a ^ b; // add without carrying
4            int carry = (a & b) << 1; // carry, but don’t add
5            return add_no_arithm(sum, carry); // recurse
6     }

Write a function to determine the number of bits required to convert integer A to integer B. Input: 31, 14 Output: 2

Each 1 in the xor will represent one different bit between A and B. We then simply need to count the number of bits that are 1.

1      public static int bitSwapRequired(int a, int b) {
2               int count = 0;
3               for (int c = a ^ b; c != 0; c = c >> 1) {
4                       count += c & 1;
5               }
6               return count;
7      }

You are given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e.g., M becomes a substring of N located at i and starting at j).

EXAMPLE:
Input: N = 10000000000, M = 10101, i = 2, j = 6
Output: N = 10001010100

This code operates by clearing all bits in N between position i and j, and then ORing to put
M in there.
1       public static int updateBits(int n, int m, int i, int j) {
2               int max = ~0; /* All 1’s */
3          
4               // 1’s through position j, then 0’s
5               int left = max - ((1 << j) - 1);
6   
7               // 1’s after position i
8              int right = ((1 << i) - 1);
9   
10              // 1’s, with 0s between i and j
11              int mask = left | right;
12   
13              // Clear i through j, then put m in there
14              return (n & mask) | (m << i);
15      }