2016-11-09 16 views
0

廣東話斯普利特和商店的hexstring我想拆分此十六進制串,轉換EM和EM存儲在數組中。 但是我的工作似乎有些不同,我不知道是什麼。在陣列

我打算把這個字符串

27CA6B

拆分

27 
CA 
6B 

但輸出永遠只有第一個字符串。 像

27 
51819 
0 

請別人幫忙,這裏是我的代碼

#include <stdio.h> 
#include <stdint.h> 
#include <stdlib.h> 
#include <string.h> 
#include <errno.h> 

int main(void) 
{ 
char bc[] = "27CA6B"; 
char *theEnd; 

long result; 
long resulta; 
long resultb; 
long resultc; 

result = strtol (bc, &theEnd, 0); 
resulta = strtol (theEnd, &theEnd, 16); 
resultb = strtol (theEnd, NULL, 0); 

//int i = 0; 
//printf("%c%c%c%c%c%c\n", bc[0], bc[1], bc[2], bc[3], bc[4], bc[5]); 

printf("%ld\n", result, &bc[0]); 
printf("%ld\n", resulta, &bc[1]); 
printf("%ld\n", resultb, &bc[2]); 


return 0; 
} 
+0

注:'CA6B'是作爲一個整體在十六進制有效。 –

+0

是的,它是一個十進制的整個CA6B,但我希望它像我的意圖分開 – user6318361

+0

究竟是什麼要求?你的第一段似乎想要將一個由6個字符組成的字符串分成3個字符串,每個字符都有兩個字符,但是你的代碼看起來像你必須轉換一個十進制數,然後是一個十六進制數,然後是另一個十進制數。長度是否固定?沒有分隔符嗎? –

回答

1

的 「問題」,你看,因爲這條線

resulta = strtol (theEnd, &theEnd, 16); 

存在的,theEndCA6B這,根據基數16,是一個整體有效的輸入,所以整個字符串被消耗和轉換。十進制表示形式值爲51819,您將其看作輸出。

實現這將是(基於你的方法)取的指針數組的起始的最佳方式,以及「剪輯」,它在備用索引。

也就是說,所有printf()語句在邏輯上是錯誤的,因爲只有一個格式說明符,但是您提供了兩個參數,因此最後一個參數將被默認忽略。

+0

我該怎麼做才能使它分開十六進制值? – user6318361

1
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main(void){ 
    char bc[] = "27CA6B"; 
    unsigned char result[(sizeof(bc)-1)/2] = {0}; 
    int i = 0; 

    for(char *p = bc; *p; p += 2){ 
     char part[3] = {0}; 
     memcpy(part, p, 2);//Extract 2 characters 
     result[i++] = strtoul(part, NULL, 16); 
    } 

    for(i = 0; i < sizeof(result); ++i){ 
     printf("%3u %c%c\n", result[i], bc[i*2], bc[i*2+1]); 
    } 

    return 0; 
} 

擴大循環

unsigned char result1,result2,result3; 
int i = 0; 
char part[3] = {0}; 

memcpy(part, bc + i, 2); i += 2; 
result1 = strtoul(part, NULL, 16); 
memcpy(part, bc + i, 2); i += 2; 
result2 = strtoul(part, NULL, 16); 
memcpy(part, bc + i, 2); i += 2; 
result3 = strtoul(part, NULL, 16); 

i = 0; 
printf("%3u %c%c\n", result1, bc[i], bc[i+1]); i += 2; 
printf("%3u %c%c\n", result2, bc[i], bc[i+1]); i += 2; 
printf("%3u %c%c\n", result3, bc[i], bc[i+1]); i += 2; 
+0

我需要將值存儲在變量中,所以我可以用它做點什麼 – user6318361

+1

@ user6318361最好使用數組而不是使用單獨的變量。 (但是,循環可以擴展。) – BLUEPIXY

+0

感謝上帝..它的完美..非常感謝你,你爲我節省了很多時間,謝謝藍色 – user6318361