【问题标题】:Convert IP address from hex to dec using strtol()使用 strtol() 将 IP 地址从十六进制转换为十进制
【发布时间】:2016-04-14 19:26:35
【问题描述】:

我将一个IP address 从框架放到结构中:

unsigned char destination_address[4];

在我的主程序中,我加载了一个结构:

struct ipv4 naglowek_ipv4;
upakuj_ipv4(bufor_eth_ipv4, &naglowek_ipv4);

并尝试以“人类可读的格式”显示此内容:

printf("Destination Adress: %ld.%ld.%ld.%ld\n",
    strtol(naglowek_ipv4.destination_address[0],NULL,16),
    strtol(naglowek_ipv4.destination_address[1],NULL,16),
    strtol(naglowek_ipv4.destination_address[2],NULL,16),
    strtol(naglowek_ipv4.destination_address[3]));

这并不像我认为的那样显示。有人知道为什么吗?

【问题讨论】:

  • (任何更熟悉“我将 IP 地址从框架放入结构”和此处其他奇怪的意思的人,请随时在编辑中澄清,谢谢)

标签: c ip hex decimal strtol


【解决方案1】:

destination_address 不是字符串,它只是四个字节的数组。因此,请简化您的调用:

printf("Destination Adress: %d.%d.%d.%d\n",
        naglowek_ipv4.destination_address[0],
        naglowek_ipv4.destination_address[1],
        naglowek_ipv4.destination_address[2],
        naglowek_ipv4.destination_address[3]);

您会注意到,如果您包含 strtol 的声明(以及您没有将足够的参数传递给最后一次调用的事实):

#include <stdlib.h> /* provides strtol() function */

【讨论】:

  • 你说得对。我太复杂了。岑你告诉我,我怎么能把一个无符号的short变成十进制?相同的例子,但 char 更改为 short: unsigned short life_time:8;
  • @AxelGocan : printf("%u", (unsigned)life_time) 或缓冲使用 `char buf[16]; sprintf(buf, "%u", (unsigned)life_time);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
  • 2015-08-10
  • 2016-07-05
  • 2023-03-05
  • 2015-06-29
  • 1970-01-01
相关资源
最近更新 更多