c语言代码 将点分十进制的IPv4地址以二进制格式输出
时间: 2023-05-26 17:05:52 浏览: 149
IP十进制点分转换为二进制
#include <stdio.h>
int main() {
char ip_address[15];
printf("Enter IP Address (XXX.XXX.XXX.XXX): ");
scanf("%s", ip_address);
// convert to binary
int oct1, oct2, oct3, oct4;
sscanf(ip_address, "%d.%d.%d.%d", &oct1, &oct2, &oct3, &oct4);
printf("%d.%d.%d.%d in binary is: ",oct1,oct2,oct3,oct4);
printf("%d%d%d%d.", (oct1 >> 7) & 1, (oct1 >> 6) & 1, (oct1 >> 5) & 1, (oct1 >> 4) & 1);
printf("%d%d%d%d.", (oct1 >> 3) & 1, (oct1 >> 2) & 1, (oct1 >> 1) & 1, oct1 & 1);
printf("%d%d%d%d.", (oct2 >> 7) & 1, (oct2 >> 6) & 1, (oct2 >> 5) & 1, (oct2 >> 4) & 1);
printf("%d%d%d%d.", (oct2 >> 3) & 1, (oct2 >> 2) & 1, (oct2 >> 1) & 1, oct2 & 1);
printf("%d%d%d%d.", (oct3 >> 7) & 1, (oct3 >> 6) & 1, (oct3 >> 5) & 1, (oct3 >> 4) & 1);
printf("%d%d%d%d.", (oct3 >> 3) & 1, (oct3 >> 2) & 1, (oct3 >> 1) & 1, oct3 & 1);
printf("%d%d%d%d", (oct4 >> 7) & 1, (oct4 >> 6) & 1, (oct4 >> 5) & 1, (oct4 >> 4) & 1);
printf("%d%d%d%d.", (oct4 >> 3) & 1, (oct4 >> 2) & 1, (oct4 >> 1) & 1, oct4 & 1);
return 0;
}
// Sample Output:
// Enter IP Address (XXX.XXX.XXX.XXX): 192.168.1.1
// 192.168.1.1 in binary is: 11000000.10101000.00000001.00000001
阅读全文