简体   繁体   English

将原始数据中的值错误转换为十六进制字符串?

[英]Wrong values in raw data to hex string convertion?

I am using the following code to convert the raw data values to a hexstring so I can find some information. 我正在使用以下代码将原始数据值转换为十六进制字符串,以便可以找到一些信息。 But I am getting FFFFFFFF where I was supposed to get FF. 但是我得到了FFFFFFFF,而我原本应该得到FF。

For example, the result should be "FF 01 00 00 EC 00 00 00 00 00 00 00 00 00 E9", but I am getting "FFFFFFFFF 01 00 00 FFFFFFEC 00 00 00 00 00 00 00 00 00 FFFFFFE9". 例如,结果应为“ FF 01 00 00 EC 00 00 00 00 00 00 00 00 00 00 E9”,但是我得到的是“ FFFFFFFFF 01 00 00 FFFFFFEC 00 00 00 00 00 00 00 00 00 00 FFFFFFE9”。

Does anyone know what is happening here? 有人知道这里发生了什么吗?

std::vector<unsigned char> buf;
buf.resize( ANSWER_SIZE);

// Read from socket
m_pSocket->Read( &buf[0], buf.size() );
string result( buf.begin(), buf.end() );
result = ByteUtil::rawByteStringToHexString( result );

std::string ByteUtil::int_to_hex( int i )
{
    std::stringstream sstream;
    sstream << std::hex << i;
    return sstream.str();
}

std::string ByteUtil::rawByteStringToHexString(std::string str)
{
    std::string aux = "", temp = "";
    for (unsigned int i=0; i<str.size(); i++) {
        temp += int_to_hex(str[i]);

        if (temp.size() == 1) {
            aux += "0" + temp + " "; // completes with 0
        } else if(i != (str.size() -1)){
            aux += temp + " ";
        }
        temp = "";
    }

    // System.out.println(aux);
    return aux;
}

UPDATE: Debugging, I noticed that the int_to_hex is returning FFFFFFFF instead of FF. 更新:调试,我注意到int_to_hex返回FFFFFFFF而不是FF。 How can I fix that? 我该如何解决?

Note the use of unsigned instead of int in int_to_hex() . 注意int_to_hex()使用unsigned而不是int

#include <iostream>
#include <sstream>

std::string int_to_hex(unsigned i)
{
    std::stringstream sstream;
    sstream << std::hex << i;
    return sstream.str();
}

int main() {
    std::cout << int_to_hex(0xFF) << "\n";
}

Output 输出量

[1:58pm][wlynch@watermelon /tmp] ./foo
ff

Additionally... 另外...

We also can see in the question you are looking at , that they do a static_cast to achieve the same result. 我们还可以在您正在查看问题中看到 ,他们进行了static_cast以获得相同的结果。

ss << std::setw(2) << static_cast<unsigned>(buffer[i]);

OK Guys, sorry for the delay, I ran into the weekend and had some FIFA World Cup games to watch. 好的,伙计们,为您的延迟感到抱歉,我遇到了周末,观看了一些FIFA世界杯比赛。

I was getting the same result no matter the change I made, so I decided to make some changes in the code before and I switched the input param from 无论我进行了什么更改,我都得到相同的结果,因此我决定在代码中进行一些更改,然后将输入参数从

std::string ByteUtil::rawByteStringToHexString(std::string str)

to

std::string ByteUtil::rawByteStringToHexString(vector<unsigned char> v)

and also kept the changes suggested by @sharth. 并保留@sharth建议的更改。 Now I am getting the correct result. 现在我得到正确的结果。

Thank you all for the help!! 谢谢大家的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM