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.
Answer

Interview Answer

6 Answers

This post has been removed.
Please see our Community Guidelines or Terms of Service for more information.

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

#include <stdio.h> main(int arg, char *argv[]) { unsigned char num, hi_indx, lo_indx, mask, num_tmp, mask_c, num_rv, iter,i; num = atoi(argv[1]); hi_indx = atoi(argv[2]); lo_indx = atoi(argv[3]); mask = ((0xFF << (7-hi_indx))) ; mask = mask >> (7-hi_indx+lo_indx); mask = (mask << lo_indx); mask_c = ~mask; num_tmp = num & mask_c; printf("%x %d %d %x",num, hi_indx, lo_indx, mask); num_rv = 0x0; iter = hi_indx-lo_indx+1; i = 0; while(i<=iter) { int flg; flg=(num & (1<<(i+lo_indx)))?1:0; if(flg) num_rv=num_rv|(1<<(hi_indx-i)); i++; } num = num_rv | num_tmp; printf("\nnum=%x ",num); }

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

Add Answers or Comments

To comment on this, Sign In or Sign Up.