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

时间:2014-03-11 21:28:14

标签: c++

我正在开发一个小嵌入式应用程序,它可以发送和响应一大堆这样的数据 {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 但这些都不是正确的价值! 提前致谢

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:0)

最后:

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

我尝试做的是来回转换从数组转换为整数,然后返回整数(我认为是从rigth端的两个字节中使用XOR?)