2015-12-29 45 views
0

我嘗試寫一個C應用程序和我使用的後續的代碼,用於讀的16個字符的輸入參數輸入字節轉換參數

int main(int argc, char *argv[]) 
{ 
    unsigned char input[16]; 

    if (argc != 2) { 
     fprintf(stderr, 
      "Usage: %s <input> \n",argv[0]); 
     return EXIT_FAILURE; 
    } 

    strncpy((char *)input, argv[1], 16); 

    return 0; 
} 

輸入參數字符是這樣的:「5f52433120d32104」(./所有MyApplication 5f52433120d32104)

我想獲得的輸入字符作爲字節,並把它放到一個數組(圖5f,52,43等),例如:

unsigned char* myByteArray; 

由於

+0

你需要將它們轉換爲hexa數嗎? – developer

+0

這是你在找什麼? http://stackoverflow.com/questions/3408706/hexadecimal-string-to-byte-array-in-c – Badministrator

回答

0

您可以使用sscanf在循環中掃描您的命令行參數。一個例子給出了一個名爲inputstr變量包含您的字符串參數:

char* inputstr = argv[1]; 
unsigned char myByteArray[ELEMENT_NO]; /*ELEMENT_NO is the number of elements to scan*/ 
for(int i = 0; i < ELEMENT_NO; ++i) 
{ 
    unsigned int value; /*The value to store the read value in*/ 
    sscanf(inputstr, "%2x", &value); /*Read 2 hexadecimal digits into value*/ 
    myByteArray[i] = value; /*Store the new value*/ 
    inpustr += 2; /*Increase 2 characters*/ 
} 

這樣myByteArray將包含讀入的unsigned char十六進制格式的數組您輸入的字符串。

如果您使用的是C99兼容編譯器,你可以使用"%2hhx"格式指示符和讀你輸入到unsigned char直接,而不是使用一箇中間unsigned int