用C语言写11001100100101000001010101110010,ip地址转换
时间: 2024-02-20 22:57:02 浏览: 34
将11001100100101000001010101110010按照每8位分割成四个字节,再将每个字节转换成十进制即可得到对应的IP地址。
用C语言实现如下:
```c
#include <stdio.h>
int main() {
char binary[] = "11001100100101000001010101110010";
int bytes[4] = {0, 0, 0, 0};
int i, j, k;
// 将二进制按照每8位分割成四个字节
for (i = 0; i < 4; i++) {
for (j = 0; j < 8; j++) {
bytes[i] = bytes[i] * 2 + (binary[i*8+j] - '0');
}
}
// 输出转换后的IP地址
printf("%d.%d.%d.%d\n", bytes[0], bytes[1], bytes[2], bytes[3]);
return 0;
}
```
输出结果为:203.73.21.114
相关问题
用c语言写ip地址转换
可以使用inet_pton和inet_ntop函数来进行IP地址的转换。inet_pton函数可以将点分十进制的IP地址转换为网络字节序的二进制IP地址,而inet_ntop函数则可以将网络字节序的二进制IP地址转换为点分十进制的IP地址。以下是示例代码:
#include <stdio.h>
#include <arpa/inet.h>
int main()
{
char ip_str[] = "192.168.0.1";
struct in_addr ip_addr;
// 将点分十进制的IP地址转换为网络字节序的二进制IP地址
if (inet_pton(AF_INET, ip_str, &ip_addr) <= 0) {
printf("Invalid IP address\n");
return -1;
}
// 将网络字节序的二进制IP地址转换为点分十进制的IP地址
char ip_buf[INET_ADDRSTRLEN];
if (inet_ntop(AF_INET, &ip_addr, ip_buf, INET_ADDRSTRLEN) == NULL) {
printf("Failed to convert IP address\n");
return -1;
}
printf("IP address: %s\n", ip_buf);
return 0;
}
ip地址转换c语言
IP地址转换成C语言字符串的代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
int main() {
struct in_addr addr;
char ip_str[INET_ADDRSTRLEN];
// 将IP地址转换为网络字节序
if (inet_pton(AF_INET, "192.168.0.1", &addr) == 0) {
perror("inet_pton");
exit(EXIT_FAILURE);
}
// 将网络字节序IP地址转换为字符串形式
if (inet_ntop(AF_INET, &addr, ip_str, INET_ADDRSTRLEN) == NULL) {
perror("inet_ntop");
exit(EXIT_FAILURE);
}
printf("IP address: %s\n", ip_str);
return 0;
}
```
这个程序将IP地址字符串"192.168.0.1"转换成网络字节序的IP地址,然后再将网络字节序的IP地址转换成字符串形式,并打印出来。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)