0
我有一個字符串(std::string
),其含有C++中的MAC地址,例如:轉換串MAC地址字節數組
10:10:0F:A0:01:00
我需要將其轉換爲一個字節數組(unsigned char*
)。
字節必須從左到右寫入。有沒有人有這個功能或有效的算法?
我有一個字符串(std::string
),其含有C++中的MAC地址,例如:轉換串MAC地址字節數組
10:10:0F:A0:01:00
我需要將其轉換爲一個字節數組(unsigned char*
)。
字節必須從左到右寫入。有沒有人有這個功能或有效的算法?
這會工作。您已將此標籤標記爲C++,因此我嚴格避免使用sscanf
C方法可能實現的較短解決方案。這裏只使用using namespace std
來縮短引用的代碼。
#include <iostream>
#include <sstream>
main() {
unsigned char octets[6];
unsigned int value;
char ignore;
using namespace std;
istringstream iss("10:10:0F:A0:01:00",istringstream::in);
iss >> hex;
for(int i=0;i<5;i++) {
iss >> value >> ignore;
octets[i]=value;
}
iss >> value;
octets[5]=value;
// validate
for(int i=0;i<sizeof(octets)/sizeof(octets[0]);i++)
cout << hex << static_cast<unsigned int>(octets[i]) << " ";
cout << endl;
}
哈哈@herohuyongtao。我不認爲這就是他的意思... – thang 2014-09-26 06:28:10
你可以使用['std :: istringstream'](http://en.cppreference.com/w/cpp/io/basic_istringstream)和'hex' I/O操作符,並使用':'作爲分隔符,將等同數字讀入6字節的數組中。 – 2014-09-26 06:28:45
好的,對不起,我忘了提及「:」 - 字符應該被刪除:-) – Crimson 2014-09-26 06:31:06