2011-06-22 45 views
0

我见过很多答案,但我似乎无法得到任何工作。我想我对变量类型感到困惑。我有一个来自NetworkStream的输入,它将十六进制代码放入String ^中。我需要把这个字符串的一部分,将其转换为一个数字(大概是int),所以我可以添加一些arithemetic,然后在窗体上输出reult。我到目前为止的代码:转换十六进制到int

String^ msg; // gets filled later, e.g. with "A55A6B0550000000FFFBDE0030C8" 
String^ test; 

//I have selected the relevant part of the string, e.g. 5A 
test = msg->Substring(2, 2); 

//I have tried many different routes to extract the numverical value of the 
//substring. Below are some of them: 

std::stringstream ss; 
hexInt = 0; 
//Works if test is string, not String^ but then I can't output it later. 
ss << sscanf(test.c_str(), "%x", &hexInt); 

//-------- 
sprintf(&hexInt, "%d", test); 

//-------- 
//And a few others that I've deleted after they don't work at all. 

//Output: 
this->textBox1->AppendText("Display numerical value after a bit of math"); 

任何帮助,将不胜感激。
Chris

+0

这不是C++。在C++中没有'String ^'。我相信这是C++/CLI,所以我将标签更改为该标签。如果我错了,请纠正我。 – sbi

+0

这个数字似乎有点太大,不适合int。 – Mankarse

+0

我只想要它的两个字符部分,而不是整个28.干杯 – Chris

回答

1

这是否对您有帮助?

String^ hex = L"5A"; 
int converted = System::Convert::ToInt32(hex, 16); 

用于Convert的静态方法的documentation位于MSDN上。

您需要停止考虑在托管类型中使用标准C++库。在.NET BCL真的是很不错...

+0

这是完美的欢呼声。我没有意识到我正在使用C++库。 – Chris

0

希望这有助于:

/* 
the method demonstrates converting hexadecimal values, 
which are broken into low and high bytes. 
*/ 
int main(){ 
//character buffer 
char buf[1]; 
buf[0]= 0x06; //buffer initialized to some hex value 
buf[1]= 0xAE; //buffer initialized to some hex value 
int number=0; 

//number generated by binary shift of high byte and its OR with low byte 
number = 0xFFFF&((buf[1]<<8)|buf[0]); 

printf("%x",number);    //this prints AE06 
printf(“%d”,number);    //this prints the integer equivalent 

getch(); 
}