c++将2字节的十六进制转换为整数

c++ convert 2 bytes of hex into integer

本文关键字:转换 整数 十六进制 字节 c++      更新时间:2023-10-16

我正在开发一个小的嵌入式应用程序,它发送和响应这样的数据块{80,09,1D,00,00}(所有值都是十六进制格式),存放在vector<int>中。我一直在寻找一种方法,将这些字节转换为类型integer (c++)。我一直在寻找,但我不能得到正确的答案,我有这个代码来测试结果:

#include <iostream>
#include<stdio.h>
#include <vector>
using namespace std;
int main()
{
    int x = 0x2008;//Expected Number Result from the process
    vector<int> aCmdResult;
    aCmdResult.push_back(0x20);
    aCmdResult.push_back(0x08);
    int aresult=0;
    aresult= (aCmdResult.at(0)&0xFF) | ( (aCmdResult.at(1)>>8)&0xFF) ;
    cout<<std::hex<<"conversion Result: "<<aresult<<endl;
    /* two bytes of hex = 4 characters, plus NULL terminator */
    x=0x0014;//Expected Number Result from the process
    aresult=0;
    aCmdResult.clear();
    aCmdResult.push_back(0x00);
    aCmdResult.push_back(0x14);
    aresult= (aCmdResult.at(0)&0xFF) | ( (aCmdResult.at(1)>>8)&0xFF) ;
    cout<<std::hex<<"conversion Result: "<<aresult<<endl;

    return 0;
}

第一个输出的结果是:0第二个是:20但这些都不是正确的价值观!提前感谢

最后:

#include <iostream>
#include<stdio.h>
#include <vector>
using namespace std;
int main()
{
    int x = 0x2008;//Expected Number Result from the process
    vector<int> aCmdResult;
    aCmdResult.push_back(0x20);
    aCmdResult.push_back(0x08);
    int aresult=0;
    aresult= ((aCmdResult.at(0)&0xFF)<<8) | ( (aCmdResult.at(1))&0xFF) ;
    cout<<std::hex<<"conversion Result: "<<aresult<<endl;
    /* two bytes of hex = 4 characters, plus NULL terminator */
    x=0x0014;//Expected Number Result from the process
    aresult=0;
    aCmdResult.clear();
    aCmdResult.push_back(0x00);
    aCmdResult.push_back(0x14);
    aresult= (aCmdResult.at(0)<<8&0xFF) | ( (aCmdResult.at(1))&0xFF) ;
    cout<<std::hex<<"conversion Result: "<<aresult<<endl;

    return 0;
}

我想做的是来回转换从数组到整数,并返回到整数(我认为这是从右边的两个字节使用异或??)

int aresult = std::accumulate( aCmdResult.begin(), std::next( aCmdResult.begin(), sizeof( int ) ), 0,
                               [] ( int acc, int x ) { return ( acc << 8 | x ); } );

如果只需要组合两个字节和sizeof(int) != 2,则替换为

std::next( aCmdResult.begin(), sizeof( int ) )

std::next( aCmdResult.begin(), 2 )

下面是使用

算法的示例
#include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <iterator>
int main()
{
    std::vector<int> v;
    v.reserve( sizeof( int ) );
    int z = 0x12345678;
    std::generate_n( std::back_inserter( v ), sizeof( int ),
                     [&]() -> int { int x = z & 0xFF; z = ( unsigned ) z >> 8; return x; } );
    std::reverse( v.begin(), v.end() );
    int x = std::accumulate( v.begin(), v.end(), 0,
                                  [] ( int acc, int x ) { return ( acc << 8 | x ); } );
    std::cout << std::hex << x << std::endl;
}