2012-03-25 54 views
0

參考第二個答案的問題:How to convert from ASCII to Hex and vice versa?Ç - 商店等值的十六進制的字符

我想保存字符六角[3]不同的字符等效如下:

char *str ="abcd"; 

// I want to get hex[3] of each character in above string and save into the following: 

char str2[4]; // should contain hex values as : \x61 for a,\x62 for b,\x63 for c,\x64 for d 

我該怎麼做?

我試過到目前爲止以下:

int i; 
char ch; 
char hex[3]; 
for(i=0; i<strlen(str);i++) { 
    ch = charToHex(*(str+i), hex); 
    // now hex contains the first and second hex characters in hex[0] & hex[1] 
    // I need to save them in the first index of str2 
    // e.g. if hex[0] = 7 and hex[1] = f, then str2[0] should be "\x7f" 

    // -> how do I do this part ? 

} 

感謝。

+7

這不是一個寫我的代碼爲我的網站。你有什麼嘗試?你卡在哪裏?還要注意,由於空終止符,字符串'「\\ x61」'可能不適合'char [4]'。 (我說「可能」,因爲如果你願意,你可以不使用空終止符而工作,但它是尷尬的,而且,我懷疑,不是你想要的。) – 2012-03-25 02:22:04

+1

答案不會以固定順序出現 - 順序依賴於upvotes和downvotes - 所以「第二個答案」是不是一個有用的描述你所指的。爲什麼不直接鏈接到你想要的答案,使用底部的「鏈接」鏈接? – ruakh 2012-03-25 02:24:26

+0

@MarceloCantos請參閱更新後的問題 – Jake 2012-03-25 02:28:23

回答

1

您可以使用for loop遍歷字符串的所有字符,然後對每個字符應用轉換。請記住C字符串是null-terminated

還要注意的是4個字符是不夠的,如果你想存儲\x61\x62\x63\x64 - 你需要4 * strlen(str) + 1,即17


爲響應代碼:

你不實際上需要chfunction charToHex返回void,即沒有。

簡單的字符複製到輸出字符串,像這樣:

str2[2*i] = hex[0]; 
str2[2*i+1] = hex[1]; 

再次,不要忘記設置空終止的結果字符串。

另外,由於您在每次迭代中都調用了strlen,因此您正在編寫一個Schlemiel the Painter algorithm

+0

我試過你的解決方案;在最後當str2使用printf(「%s」,str2)打印時,它打印出61626364. 現在我的問題是,我有:char * str3 =「\ x61 \ x62 \ x63 \ x64」這與我們得到的結果相同,因爲目標是從str1轉換爲str3格式。 – Jake 2012-03-25 03:05:04

+0

好吧,如果你想要一個額外的'\ x',你可以簡單地將每四個字符設置爲''\\'',並且每四個字符(從第二個開始)設置爲''x''。代碼保持不變;只需用'4 * i'替換'2 * i'即可。 – phihag 2012-03-25 03:08:16

+0

尺寸會有變化嗎? – Jake 2012-03-25 03:09:19

相關問題