我有一個字符數組(像aa:bb:cc:dd:ee:ff
這樣的以太網地址),我需要解析成unsigned char[6]
。我使用strtok來獲取每個字符對,並且我需要將它們轉換爲一個無符號字符,但是我所做的一切都沒有發揮作用。將char *長度2轉換爲無符號字符的正確方法?
我嘗試(假設c
是長度爲2的一個char *):
unsigned char t = (unsigned char)c; // gives "loses precision" error
unsigned char* t = (unsigned char*)c;
unsigned char t1 = t[0]; // gives the wrong value
unsigned char t;
strcpy((char*)t, c); // gives the wrong value
strncpy((char*)t, c, sizeof(char)*2) // gives the wrong value
「c」是如何定義的?你的'strncpy'代碼也有錯誤。 – 2012-04-21 17:44:59
@macs固定。往上看。 – xdumaine 2012-04-21 17:46:05
你試過['strtoul(c,NULL,16)'](http://www.cplusplus.com/reference/clibrary/cstdlib/strtoul/)嗎?它可能會給你「失去精度」的警告,但會產生一個無符號整數(第一個令牌的值爲'0xAA'等)。 – DCoder 2012-04-21 17:47:27