2016-11-07 63 views
-1

enter image description here如何將「3位」字段從下面提到的字符串格式

嗨,取

說我有串像「888820c8」。我如何獲取3位在C編程語言int?

更新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; 
} 
+0

這不是「字符串格式」。但要解決你的問題,編寫一個程序將是一個好主意。隨意問一個**具體**問題,如果這些飛艇。請記住提供[mcve]並按照[問]的建議。 – Olaf

+2

而「掩蔽」和「位移」可能是一個很好的條件,開始你的研究。 –

+0

如果它首先是文本格式,則可以應用strtol將其轉換爲內部二進制表示形式,然後應用一個掩碼和一個移位,或一個移位和一個掩碼。但你有什麼嘗試?我們不喜歡在你似乎沒有開始的地方發佈輕拍解決方案。 –

回答

1

,你必須的代碼所處的字符包含你想要的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; 
} 
+0

加一個說明! – Coder

1

閱讀該字符串的字符數組 Char數據[8] = 「888820c8」 (數據[4] & 0xe0的)>> 5是你的答

+0

只需要使用一個面具 – nopasara