如何从下面提到的字符串格式中获取“3 位”字段

How to fetch the '3 bits' field from the below mentioned string format

嗨,

假设我有像“888820c8”这样的字符串。我如何在 c 编程语言中获取 int 中的 3 位?

更新 1 -

这就是我能做到的

static const char* getlast(const char *pkthdr)
{
    const char *current;
    const char *found = NULL;
    const char *target = "8888";
    int index = 0;
    char pcp = 0;

    size_t target_length = strlen(target);
    current = pkthdr + strlen(pkthdr) - target_length;

    while ( current >= pkthdr ) {
        if ((found = strstr(current, target))) {
            printf("found!\n");
            break;
        }
        current -= 1;
    }

    if(found)
    {
        index = found - pkthdr;
        index += 4; /*go to last of 8188*/
    }
    printf("index %d\n", index);
     /* Now how to get the next 3 bits*/

    printf("pkthdr %c\n", pkthdr[index]);

    pcp = pkthdr[index] & 0x7;
    printf("%c\n", pcp);
    return pcp;
}

很明显,我知道程序的最后一部分是错误的,任何输入都会有所帮助。谢谢!

更新 2:

感谢 pratik 指点。 下面的代码现在看起来不错吗?

static char getlast(const char *pkthdr)
{
    const char *current;
    const char *found = NULL;
    const char *tpid = "8188";
    int index = 0;
    char *pcp_byte = 0;
    char pcp = 0;
    int pcp2 = 0;
    char byte[2] = {0};
    char *p;
    unsigned int uv =0 ;

    size_t target_length = strlen(tpid);
    current = pkthdr + strlen(pkthdr) - target_length;
    //printf("current %d\n", current);

    while ( current >= pkthdr ) {
        if ((found = strstr(current, tpid))) {
            printf("found!\n");
            break;
        }
        current -= 1;
    }

    found = found + 4;

    strncpy(byte,found,2);
    byte[2] = '[=11=]';

    uv =strtoul(byte,&p,16);

    uv = uv & 0xE0;
    char i = uv >> 5;
    printf("%d i",i);
    return i;
}

读取这个字符串字符数组 字符数据[8] = "888820c8" (data[4]&0xe0) >> 5 是你的答案

您所拥有的代码定位了包含您想要的 3 位的字符。该字符将是数字('0''9')、大写字母('A''F')或小写字母('a''f').因此,第一个任务是将字符转换为其等效的数字,例如像这样

unsigned int value;
if ( sscanf( &pkthdr[index], "%1x", &value ) != 1 )
{
    // handle error: the character was not a valid hexadecimal digit
}

此时,你有一个4位的值,但你想提取高三位。这可以通过移位和屏蔽来完成,例如

int result = (value >> 1) & 7;
printf( "%d\n", result );

注意,如果要return函数中的3位数,需要将函数原型改为return和int,例如

static int getlast(const char *pkthdr)
{
    // ...
    return result;
}