converting a string to byte (unsigned char) array cpp

前端 未结 1 964
栀梦
栀梦 2021-02-04 22:58

having real trouble with this simple issue. I have a string like this:

std::string msg = \"00 00 00 00 00 06 01 05 00 FF 00 00\";

which i would

1条回答
  •  无人及你
    2021-02-04 23:10

    If at all possible, I'd advise using a std::vector instead of an actual array.

    Using that, I guess I'd do something like this:

    std::istringstream buffer(msg);
    
    std::vector bbuffer;
    
    unsigned int ch;
    while (buffer >> std::hex >> ch)
        bbuffer.push_back(ch);
    

    If you really insist on the array, you could do something like:

    std::istringstream buffer(msg);
    
    char bbuffer[12];
    
    unsigned int ch;
    for (int i=0; buffer >> std::hex >> ch; i++)
        bbuffer[i] = ch & 0xff;
    

    But the vector is usually preferable.

    0 讨论(0)
提交回复
热议问题