看到了一篇面经里关于二进制调转的题目,即给定一个整数a, 输出其二进制格式和将二进制中头尾对应位互换的结果。
题目考查的应该是对于位的操作。不过应该也可以换个思路,把a的二进制输出成字符串并对其进行头尾对调。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void invert(char* buff){
int length = strlen(buff);
int i;
char temp;
for(i=0;i<length/2;i++){
temp = buff[length-i-1];
buff[length-i-1] = buff[i];
buff[i] = temp;
}
}
int atoiB(const char* buff){
int b=0,i,length=strlen(buff);
for(i=length;i>0;i--){
b*=2;
b += (buff[i-1] - '0');
}
return b;
}
int main(){
int a = 6;
char buff[100];
itoa(a,buff,2);
printf("initial value of a is %s\n",buff);
invert(buff);
printf("after switch, value is %s and correspoind initial value is \n",buff,atoiB(buff)); //验证
system("pause");
return 0;
}