简体   繁体   English

C++:十六进制值到字符串

[英]C++: Hex values to String

I would like to convert a hex-value ("206564697374754f") to a string (from hex to ascii).我想将十六进制值(“206564697374754f”)转换为字符串(从十六进制到 ascii)。 These hex-values are from gdb, so the contents are "reversed" by every two .这些十六进制值来自 gdb,因此每两个. (So the exact hex-value I need to convert is "4f75747369..."). (所以我需要转换的确切十六进制值是“4f75747369...”)。 reverse2() reverses the string appropriately, but it needs to now be converted to hex (hence the "0x", then atoi() ). reverse2()适当地反转字符串,但现在需要将其转换为十六进制(因此是“0x”,然后是atoi() )。

The following code is what I have so far, but I run into a runtime-error.以下代码是我到目前为止所拥有的,但我遇到了运行时错误。 What is the issue, and is there a better way of doing this?这是什么问题,有没有更好的方法来做到这一点?

#include <bits/stdc++.h> 
using namespace std; 

void reverse2s(string str) 
{ 
for (int i=str.length()-2; i>=0; i-=2) {
    string hx="0x"+str[i]+str[i+1];
    cout << (char)(std::stoi( hx )); 
}
} 

// Driver code 
int main(void) 
{ 
    string s = "206564697374754f"; 
    reverse2s(s); 
    return (0); 
} 

The expression "0x"+str[i]+str[i+1];表达式"0x"+str[i]+str[i+1]; does not do what you think.不做你想的。 "0x" is a character array (not a string). "0x"是一个字符数组(不是字符串)。 Since str[i] is a character, the addition will add convert that character to an int, and perform a pointer addition.由于str[i]是一个字符,加法会将该字符转换为 int,并执行指针加法。 This results in Undefined Behavior.这会导致未定义行为。

To do the string concatenation you're expecting, you need to create a string object first:要进行您期望的字符串连接,您需要先创建一个字符串对象:

string hx="0x"s+str[i]+str[i+1];

"0x"s will create an actual string literal to append characters to. "0x"s将创建一个实际的字符串文字来追加字符。

Well it seems like you're just trying to print it as hex,好吧,您似乎只是想将其打印为十六进制,

so you could do所以你可以这样做

std::cout << std::hex << 5 << std::endl; // prints 0x5

If you don't care about performance:如果你不关心性能:

std::stringstream s;
s << std::hex << num:
s.str(); // std::string containing your number as hex

If you do care about performance I have no clue如果你真的关心性能,我不知道

This should work:这应该有效:

#include <iostream>
#include <strstream>
#include <string>

int main()
{
    std::strstream s1; // dynamic buffer
    s1 << std::hex << 12345 << std::endl;
    std::cout << "buffer: '" << s1.str() << "'\n";
    s1.freeze(false);
    return 0;
}

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

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