Bulild字符串变量,它实际上是一个十六进制数

问题描述:

说我有string变量:Bulild字符串变量,它实际上是一个十六进制数

string str1 = "\x11"; 

说我想手动建立这个string,意义,我有:

string str2 = "11" 

,并希望天真地做:

string str3 = '\x' + "11" 

有没有办法以str3 == str1这样的方式构建str3

+1

STR3总是等于STR3 – Geoffroy 2014-09-11 12:14:46

+0

10倍。固定的。 – idanshmu 2014-09-11 12:21:34

是这样的:

std::stringstream ss; 
ss << (char) 0x11; 
std::string str3 = ss.str(); 

有了:

#include <string> 
#include <sstream> 

或者,如果你真的有 “11” 字符串开头:

std::string value = "11"; 
std::stringstream temp; 
temp << std::hex << value; 
char c; 
temp >> c; 
std::stringstream ss; 
ss << c; 
+2

应该是'0x11'。 – timrau 2014-09-11 12:12:12

+0

@timrau:谢谢,修正了这个问题。 – 2014-09-11 12:12:32

+0

@Martijn Courteaux它工作正常。如果你能够用几句话说出第一种方法的作用,我会很高兴。 – idanshmu 2014-09-11 13:01:06

如果先有自己的整数低于256那你就可以做

int small = 17; // 0x11 hex 
sanity check here 
str[0] = (char)small; 

如果你开始用绳子

int small = HexToInt("11"); // 0x11 hex, find a HexToInt on the next. 
sanity check here 
str[0] = (char)small;