I am a C++ developer and shifted to wpf last week. Well I have used sprintf in my c++ apps many time and now I have across the need of having something equivalent to that in C#. Here is what I had done is C++:
char t_str[4] = {};
for(int i = 0; i < 4; i++)
{
sprintf(t_str, "%02X", buffer[i]);
m_apiResponse[i]->setText(String(t_str));
}
where buffer[0] = 20; and
buffer[1] = 30;
buffer[2] = 40;
buffer[3] = 50;m_apiResponse is a textbox.
I had done this in my C# as follows:
Byte[] t_str = new Byte[4];
for (int i = 0; i < 4; i++)
{
string bufstring = String.Format("{0:02}", buffer[i]);
t_str = Encoding.UTF8.GetBytes(bufstring);
}
Response1Box = Convert.ToString(t_str[0]);
Response2Box = Convert.ToString(t_str[1]);
Response3Box = Convert.ToString(t_str[2]);
Response4Box = Convert.ToString(t_str[3]);
where ResposeBox is a textbox which I have bind to:
// Description of Response1Box
private string _Response1Box;
public string Response1Box
{
get
{
return _Response1Box;
}
set
{
_Response1Box = value;
OnPropertyChanged("Response1Box");
}
}
buffer[64] is byte[].
Its not giving me the expected answer which my C++ method does. Is this the right way to do: string bufstring = String.Format("{0:02}", buffer[i]); Where am i wrong???
t_str = Encoding.UTF8.GetBytes(bufstring);
Please help 🙂
Try with
or (for hex output)
or (with C/C++ style hex prefix)
See Composite Formatting and Standard Numeric Format strings
Of course, inside the C++ loop you call the
m_apiResponse[i]->setText, you should do something similar in the C# loop to achieve the same result.UPDATE: It is not clear to me what ResponseBox is, but if you have 4 string properties named Response[X]Box inside an object instance called ResponseBox then you could set these properties outside the loop in this way