465 views
0 votes
0 votes
long fun(char *s) {

long r=0;

for(; *s; r=(r<<1)|(*s++ - '0'));

return r;

}

what does fun("000001010") return??

1 Answer

0 votes
0 votes

fun("000001010")  will return decimal value of 000001010 i.e. 10

r is initialised to 0

for(; *s; r=(r<<1)|(*s++ - '0'));

*s is condition checking here and will fail when we will reach end of string 000001010

*s++ will point pointer s to next bit of the string

initially r=0 //r will remain 0 until first bit of input string is 1 so r=0 for string 00000

then r=(0000<<1) OR(1-0)                  //000001

           =0000 OR 0001

          =0001

     

r=(0001<<1) OR(0-0)                        //0000010

           =0010 OR 0000

          =0010

             

r=(0010<<1) OR(1-0)                       //00000101

           =0100 OR 0001

          =0101

 

r=(0101<<1) OR(0-0)                      //000001010

           =1010 OR 0000

          =1010

so r=1010 will be returned whose decimal value is 10

Related questions

1 votes
1 votes
2 answers
1
vaishali jhalani asked Nov 9, 2016
1,305 views
#include <stdio.h>char *fun(){ static char arr[1024]; return arr;} int main(){ char *str = "geeksforgeeks"; strcpy(fun(), str); str = fun(); strcpy(str,...
0 votes
0 votes
1 answer
2
AVINASH YADAV asked Jul 1, 2016
3,078 views
main() {int a,b,c,d;a=3,b=5;c=a,b;d=(a,b);printf("%d %d",c,d);}Output???
2 votes
2 votes
1 answer
3
manisha11 asked Sep 13, 2018
670 views
Declare an array of N pointers to functions returning pointers to functions returning pointers to characters?A) (char*) (*ptr[N])( )(B) (char*(*)) (*ptr[N])( )(C) (char*(...
1 votes
1 votes
2 answers
4
Amit puri asked Sep 20, 2016
380 views
how to calcuate the address