十进制到十六进制函数在C ++ / CLI中 [英] Decimal to Hexadecimal Functions in C++/CLI
问题描述
我有一个程序通过串行端口与设备通信。我有一个部分的困难。当我运行计算的十六进制命令时,我得到了一个直角符号。这是代码的两个部分(主要部分和函数)。
I have a program that communicates to a device through the serial port. I am having difficulties with one section however. I am getting what looks like a right angle symbol when I run through the calculated hexadecimal commands. Here are the two sections of code (main section and function).
主要部分:
private: System::Void poll_Click(System::Object^ sender, System::EventArgs^ e)
{
int i, end;
double a = 1.58730159;
String^ portscan = "port";
String^ translate;
std::string portresponse [65];
std::fill_n(portresponse, 65, "Z");
for (i=0;i<63;i++)
{
if(this->_serialPort->IsOpen)
{
// Command 0 generator
int y = 2;
y += i;
std::string command0[10] = {"0xFF", "0xFF", "0xFF", "0xFF", "0xFF", "0x02", dectohex(i), "0x00", "0x00", dectohex(y)};
// The two "dectohex" values above is where I get the odd symbol
for (end=0;end<10;end++)
{
portscan = marshal_as<String^>( command0[end] );
this->_serialPort->WriteLine(portscan);
}
translate = (this->_serialPort->ReadLine());
MarshalString(translate, portresponse [i]);
if(portresponse [i] != "Z")
{
comboBox7->Items->Add(i);
}
this->progressBar1->Value=a;
a += 1.58730159;
}
}
}
功能:
string dectohex(int i)
{
string hexidecimal = "";
char hex_string[10] = "";
hexidecimal = sprintf (hex_string, "0x%02X", i);
return hexidecimal;
}
我假设有一些相当简单的缺失。
I am assuming that there is something fairly simple that I am missing. Any and all help is appreciated.
解决方案:
根据David Yaw的指导。
The solution: Per David Yaw's guidance.
string dectohex(int i)
{
char hex_array[10];
sprintf (hex_array, "0x%02X", i);
string hex_string(hex_array);
return string(hex_string);
}
推荐答案
sprintf
不是一个字符串,因为您当前编码。它是写入作为第一个参数传递的 char *
的字符数。使用您传递的字符缓冲区,并将 char *
转换为字符串对象。
The return value of sprintf
isn't a string, as you have coded currently. It's the number of characters written to the char*
that was passed in as the first parameter. Use the character buffer that you passed in, and convert the char*
to a string object.
string dectohex(int i)
{
char hex_string[10];
sprintf (hex_string, "0x%02X", i);
return string(hex_string);
}
这篇关于十进制到十六进制函数在C ++ / CLI中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!