c++ - 将无符号字符指针解析为位操作数 C++

标签 c++ linux pointers binary

我有一个指向原始以太网数据包的指针,我想打印它的 IP 版本。我在 Linux 客户端上使用 C++。

IP 版本与 IHL(Internet Header Length)一起存储在包头的第 14 个字节。我有一个打印 IP header 中所有字段的函数,但由于 IP 版本与 IHL 一起存储在第 14 个字节中,我必须在第 14 个字节中打印前 4 位,我不知道如何执行此操作。我想同时打印 IP 版本和 IHL。

我的函数是这样的:

int PrintIPHeader(unsigned char *eth_head)
{
    unsigned char *ip_head = eth_head;
    int j;

    printf("---Start of IP Header---");
    printf("\nVersion\n");
    for(j = 0; j < 1; j++)
    {
        printf("%d", *(ip_head+j));
    }

    printf("\nIHL\n");
    for(j = 0; j < 1; j++)
    {
        printf("%d", *(ip_head+j));
    }

    printf("\nToS\n");
    for(j = 1; j < 2; j++)
    {
        printf("%d", *(ip_head+j));
    }

    printf("\nTotal Length\n");
    for(j = 2; j < 4; j++)
    {
        printf("%d", *(ip_head+j));
    }

    ...
    and so and so on with all the fields of an IP header 
    (I know the for-loop is unnecessary in some of the cases)
}

上面的方法打印了整个字节,但我想要的是它只打印前 4 位,然后我想要另一个“printf”来打印第一个字节的最后 4 位。在上述方法中,我将 header 的第 14 个字节解析为参数。

我被告知我可以使用以下命令将前四位切换 4 个位置,从而覆盖 IHL,这不是我想要的。

printf(ip_head[14] >> 4); 

但我得到一个错误“'unsigned char *' 和 'int' 类型的操作数对二进制 'operator>>' 无效”。

谁有解决办法?

最佳答案

如果你使用这个命令

printf(ip_head[14] >> 4); 

这些位不会被永久覆盖。 您可以将行为与

printf(a + 4);

其中 a 仍然保留以前的值,但 printf 被移交了 a+4 的值。

关于c++ - 将无符号字符指针解析为位操作数 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19904486/

相关文章:

c - C 中字符串数组的值增加

c++ - Poco C++ Websocket 服务器 - 防止它在 60 秒后关闭

mysqladmin ping错误代码

linux - NASM "error: comma, colon, decorator or end of line expected after operand"

linux - 在linux中使用mplayer播放YUV视频

c - 数组作为函数的参数

c++ - C++中的二维对象数组

java - 如何使用简单的高斯分布算法将点分布在平面上?

c++ - 在包含 float 的结构上使用 memset()

c++ - 如何为模板化类型提供 void* 访问器?