[英]converting a string to byte (unsigned char) array cpp
在這個簡單的問題上遇到了麻煩。 我有一個像這樣的字符串:
std::string msg = "00 00 00 00 00 06 01 05 00 FF 00 00";
我想:
unsigned char bbuffer[12] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x01, 0x05, 0x00, 0xFF, 0x00, 0x00 };
怎么做呢?
如果可能的話,我建議使用std::vector<unsigned char>
而不是實際的數組。
使用它,我想我會做這樣的事情:
std::istringstream buffer(msg);
std::vector<unsigned char> bbuffer;
unsigned int ch;
while (buffer >> std::hex >> ch)
bbuffer.push_back(ch);
如果您真的堅持使用數組,則可以執行以下操作:
std::istringstream buffer(msg);
char bbuffer[12];
unsigned int ch;
for (int i=0; buffer >> std::hex >> ch; i++)
bbuffer[i] = ch & 0xff;
但是向量通常是可取的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.