C language binary number by bit output example
- 2020-04-02 02:16:03
- OfStack
Ask questions:
1. Input int 20, whose binary value is 10100, and output 10100 by bit;
2. Or convert 1 to "+", and 0 to "-", and the output is "+ - + -";
Solutions:
int biTofh(int bi,int len){//Binary converts to plus and minus
int i=0;
while(i<len){
int tmp = 1;
if((bi & (tmp<<(len-i-1))) != 0){//Let's start with the leftmost bit, which is 1
printf(" + ");
}
else{
printf(" - ");
}
i++;
}
printf("n");
return 0;
}
int main(){
int input[] = {1,2,3,4,5};
biTofh(20,5);
return 0;
}
Output results:
xu@xu-ThinkPad-X61:~/algorithm$ ./a.out
+ - + - -
xu@xu-ThinkPad-X61:~/algorithm$