C++:将无符号长整型转换为矢量<uint8_t>原始数据



我需要将long int x = 0x9c758d0f转换为vector<uint8_t> y = 9c 75 8d 0f

我正在使用:

std::stringsteam ss;
ss << std::hex << x;
std::string s = ss.str();
std::vector<uint8_t> y;
String2Vector(s,y);
    void String2Vector(std::string& in, std::vector<uint8_t>& output) 
    {
        std::vector<uint8_t> out;
        size_t len = in.length();
        for(size_t i = 0; i < len; i += 1) 
        {
            std::stringstream strm(in.substr(i, 1));
            uint8_t x;
            strm  >>std::hex>> x;
            out.push_back(x);
        }
        output = out;
    }

但是,vector<uint8_t>存储 ASCII 数字而不是十六进制值。

我应该怎么做才能将long int转换为原始数据向量?这是一个多平台项目,所以我不想碰memcpy()等。


更新:很确定出了问题:

long int x = 0x9c758d0f;
std::vector<uint8_t> v;
v.reserve(sizeof(x));
for (size_t i = 0; i < sizeof(x); ++i) {
    v.push_back(x & 0xFF);
    x = (x>>8);
}
PrintOutVector(v);
void PrintOutVector(std::vector<uint8_t>& in)
    {
        std::cout << "Vector Contains: ";
        for(std::vector<uint8_t>::iterator i=in.begin(); i != in.end(); ++i)
            std::cout << std::hex <<  *i ;
        std::cout << "n";
    }

输出为 ▒C▒▒h4


解决方案:非常感谢@WhozCraig @Anton萨文

long int x = 0x9c758d0f;
std::vector<uint8_t> v;
v.reserve(sizeof(x));
for (size_t i = 0; i < sizeof(x); ++i) {
    v.push_back(x & 0xFF);
    x = (x>>8);
}
PrintOutVector(v);
void PrintOutVector(std::vector<uint8_t>& in)
    {
        std::cout << "Vector Contains: ";
        for(std::vector<uint8_t>::iterator i=in.begin(); i != in.end(); ++i)
            std::cout << std::hex <<  static_cast<unsigned int>(*i)
        std::cout << "n";
    }

这是一个解决方案,无论字节顺序如何,它都能提供相同的结果:

long int x = 0x9c758d0f;
std::vector<uint8_t> v;
v.reserve(sizeof(x));
for (size_t i = 0; i < sizeof(x); ++i) {
    v.push_back(x & 0xFF);
    x >>= 8;
}
long int x = 0x9c758d0f;
const uint8_t* begin = reinterpret_cast<const uint8_t*>(&x);
const uint8_t* end = begin + sizeof(x);
std::vector<uint8_t> v(begin, end);

请注意,排序取决于系统如何排列long中的字节(大端序或小端序(。 你可以通过首先使用像 htonl(( 这样的函数将字节重新排序为大端来处理这个问题,除了这是用于int的,并且没有跨平台的long所以你必须考虑如果你关心字节排序,在那里做什么。

工会

在这类事情上派上用场。唯一的问题是字节顺序可能会因字节序而异,您必须考虑这一点。

union U{
    long int i;
    uint8_t uc[4];
};
U u = {0x9c758d0f};
std::vector<uint8_t> ucvec(u.uc, u.uc+4);
printf ("%x:%x:%x:%xn", ucvec[3], ucvec[2], ucvec[1], ucvec[0]);

相关内容

最新更新