Qualcomm

www.qualcomm.com
Engaged Employer

## Interview Question

Interview Santa Clara, CA

# Write a c functions that takes two bit indices and an int

, and reverses the bits in the int between the two indices.

This post has been removed.

0

//reverses bit between two indices of a number. #include<iostream> using namespace std; int main() { unsigned int no=90,i=2,j=6,tmp=0,tmp1=0; tmp=no>>i; cout<<tmp<<" tmp\n"; for(unsigned int x=0;x<=j-i;x++) { tmp1=tmp1<<1; tmp1=tmp1|(tmp&1); tmp=tmp>>1; } cout<<tmp1<<"tmp1 \n"; tmp=0; for(unsigned int x=0;x<=(int)(sizeof(int)*8-1);x++) { tmp=tmp>>1; if(x<=j && x>=i) tmp=tmp|0; else tmp=tmp|0x80000000; } cout<<tmp<<"tmp before\n"; no=no&tmp; no=no|(tmp1<<i); cout<<no<<" no"; return 0; }

noty on Apr 1, 2011
1

Anonymous on Nov 3, 2012
0

The above one is just to give an example with 8bits

Anonymous on Nov 4, 2012
0

#include <stdio.h> int toggle_bw_indices(int num, int hi_index, int lo_index) { int count = 1; // assume 0th position as index 1 int res = num; while (num) { if (count >= lo_index && count <= hi_index) // if in pattern { res ^= (1 << (count - 1)); } num = num >> 1; count++; } return res; } int main() { int num = 90; int hi_index = 5; int lo_index = 2; printf("%d\n", toggle_bw_indices(num, hi_index, lo_index)); return 0; }

Suomynona on Mar 17, 2015
1

int toggle_bw_indices(int num, int hi_index, int lo_index) { int rev_nib(0),rev(0); int mask_nib, mask; int nib(0); mask_nib = 0xF; mask = ~mask_nib; rev = (mask & num); nib = (mask_nib & num); for (int i=0; i<4; ++i) { if (i>=lo_index && i<=hi_index) { if (nib & (1<< (hi_index+lo_index-i))) rev_nib += 1<<i; } else { rev_nib += nib & (1<<i); } } rev += rev_nib; return rev; } int _tmain(int argc, _TCHAR* argv[]) { int num = 90; int hi_index = 2; // hi and lo index can be bwteen 0 and 3 (2 bits) int lo_index = 0; printf("%d\n", toggle_bw_indices(num, hi_index, lo_index)); }

joon on May 10, 2015