位转换
16转8
//16转8 #include <stdio.h> #include <string.h> char str[100005], num; void Fun(int i, int state) //长度 位数 { int temp; if(i < 0) { if(num != 0) //此时的num转二进制后的有效位数小于三位,即num小于8 { printf("%d", num); } return; } if(state != 3) { temp = str[i] >= '0' && str[i] <= '9' ? str[i] - '0' : str[i] - 'A' + 10; temp <<= state; //state指每次将16进制转2进制后,截取最后三位后剩余几位 num |= temp; //把二进制的num和二进制的temp相加(等同于十进制之间的加,因为对应num位数的temp的后几位在上一步左移时填补了0) temp = num; num >>= 3; Fun(i - 1, state + 1); printf("%d", (temp & 1) + (temp & 2) + (temp & 4)); //相当于将temp转二进制后的最后三位取出并转8进制 } else { temp = num; num >>= 3; Fun(i, 0); printf("%d", (temp & 1) + (temp & 2) + (temp & 4)); } } int main() { int n; scanf("%d", &n); while(n--) { num = 0; scanf("%s", str); //输入 Fun((int)strlen(str) - 1, 0); printf(" "); } return 0; }
10转2转16
//十进制转2进制 转16进制 #include <stdio.h> #include <string.h> int inttoBin(unsigned int num) { int i; unsigned int mask = 0x80000000; for(i = 0; i < 32; i++) { if((num & mask) == mask) { printf("1"); } else { printf("0"); } num = num << 1; if((i + 1) % 4 ==0) { printf(" "); } } printf(" "); } int inttoox(unsigned int num) { int i; unsigned int temp = num; char s[11]; memset(s,0,sizeof(char)); s[0] = '0'; s[1] = 'x'; s[10] = '