2011-06-22 111 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(); 
}