字符串到字节数组

时间:2010-04-04 18:34:43

标签: c++ c

如何输入DEADBEEF并输出DE AD BE EF作为四字节数组?

2 个答案:

答案 0 :(得分:4)

void hexconvert( char *text, unsigned char bytes[] )
{
    int i;
    int temp;

    for( i = 0; i < 4; ++i ) {
        sscanf( text + 2 * i, "%2x", &temp );
        bytes[i] = temp;
    }
}

答案 1 :(得分:2)

听起来你想将字符串解析为十六进制整数。 C ++方式:

#include <iostream>
#include <sstream>
#include <string>

template <typename IntType>
IntType hex_to_integer(const std::string& pStr)
{
    std::stringstream ss(pStr);

    IntType i;
    ss >> std::hex >> i;

    return i;
}

int main(void)
{
    std::string s = "DEADBEEF";
    unsigned n = hex_to_integer<unsigned>(s);

    std::cout << n << std::endl;
}