c - 下面的格式说明符在做什么?

标签 c printf

         else
        {
            printf("\\%.3hho", *data);
        }

我无法在网上或通过阅读 C 编程语言书籍找到有关如何破译它的信息。我在下面的代码片段中看到了它。该代码尝试在 telnet 协议(protocol)中执行密码嗅探。

if ((pktlen - sizeof(struct ipheader)) >  dataoffset)
{
    printf("   SrcIP: %s,", inet_ntoa(ip->iph_sourceip));
    printf(" DstIP: %s,", inet_ntoa(ip->iph_destip));
    printf(" Data: ");
    u_char* data = (u_char*)tcp + dataoffset;

    for (unsigned short s = 0; s < (ntohs(ip->iph_len) - (sizeof(struct ipheader) + dataoffset)); s++)
    {
        if (isprint(*data) != 0)
        {
          printf("%c", *data);
                                  }
        else
        {
            printf("\\%.3hho", *data);
        }
        data++;
    }
    printf("\n");
  }

}

最佳答案

根据CppReference :

Conversion specifier o

converts a unsigned integer into octal representation oooo,

Precision specifies the minimum number of digits to appear. <truncated>

因此字符串 \\%.3hho 表示一个文字反斜杠(已转义),加上格式说明符 %.3hho:

  • %...o 表示无符号整数的八进制表示。字母 o 也表示此说明符的结尾
  • hh 是 C99 规范,表示 unsigned char 而不是 unsigned int,始终是单个字节
  • .3 表示精度为 3,因此至少 3 个八进制数字 (000 - 377)

关于c - 下面的格式说明符在做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66020521/

相关文章:

c - 为什么解释为 double 的整数会呈现零?

c - 根据平台选择功能名称的最标准方法?

c++ - 带指针的 bitWrite 函数

c++ - 如何将数组指向嵌入式系统上的某个特定内存地址

c++ - 在Arduino的C++中使用可变参数模板编写自定义[s] printf

c - 仅使用 While 循环和 If 语句用 C 绘制 X

c++ - 函数可以访问传递给 main() 的参数吗?

c - 如何将 CMake 的输出重定向到文件而不是 Windows cmd 提示符

c - 为什么即使文件存在并且正确打开和关闭, fprintf() 也不打印任何内容?

java - 相邻打印 2 个 HashMap