如何获取 3位'来自下面提到的字符串格式的字段

时间:2016-11-07 17:54:45

标签: c bitwise-operators bit

enter image description here

您好,

说我有#34; 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] = '\0';

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

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您拥有的代码可以找到包含所需3位的字符。该字符将为数字('0''9'),大写字母('A''F')或小写字母('a'至{{1 }})。所以第一个任务是将字符转换为数字等价物,例如像这样

'f'

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

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

请注意,如果要从函数返回3位数字,则需要更改函数原型以返回int result = (value >> 1) & 7; printf( "%d\n", result ); ,例如

int