开发者

string to byte array

开发者 https://www.devze.com 2022-12-26 04:30 出处:网络
How do I input DEADBEEF and output DE AD BE EF as four byte ar开发者_如何学Pythonrays?void hexconvert( char *text, unsigned char bytes[] )

How do I input DEADBEEF and output DE AD BE EF as four byte ar开发者_如何学Pythonrays?


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;
    }
}


Sounds like you want to parse a string as hex into an integer. The C++ way:

#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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消