C 如何获取';3位';下面提到的字符串格式中的字段

C 如何获取';3位';下面提到的字符串格式中的字段,c,bitwise-operators,bit,C,Bitwise Operators,Bit,嗨 假设我有类似“888820c8”的字符串。在c编程语言中,如何获取整数中的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_le

假设我有类似“888820c8”的字符串。在c编程语言中,如何获取整数中的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:

谢谢普拉蒂克的指点。 下面的代码现在看起来不错吗

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] = '\0';

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

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

读取这个字符串字符数组 字符数据[8]=“888820c8”
(数据[4]&0xe0)>>5是您的ans

您拥有的代码用于定位包含所需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 );
请注意,如果要从函数返回3位数字,则需要更改函数原型以返回
int
,例如

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

这不是“字符串格式”。但要解决您的问题,编写程序将是一个好主意。如果有问题,请随意提问。请记住提供并遵循中的建议。从“掩蔽”和“位移位”开始您的研究可能是一个很好的术语。如果是文本格式,您可以先应用
strtol
将其转换为内部二进制表示,然后应用掩蔽和移位,或移位和掩蔽。但是你试过什么?我们不喜欢在你似乎还没有开始的地方发布pat解决方案。你应该更好地阐述你的问题只是不需要使用maskplus来解释!