Reputation: 397
I am a C++ developer and recently shifted to C#. I am working on a wpf app where I need to work on String.Format
. In My C++ application, I had used sprintf
to obtain the result but when it comes to C#, string.format helped me achieve it. Now I have come across a tricky situation where I need to achieve the similar thing but with different values. Here Is the C++ code:
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;
buffer[1] = 30;
buffer[2] = 40;
buffer[3] = 50;
and m_apiResponse
is a textbox.
Even though string.format
was also helpful, I rather choose the easiset way of doing it. I had done this in my C# as follows:
Response1Box = buffer[0].ToString("X2");
Response2Box = buffer[1].ToString("X2");
Response3Box = buffer[2].ToString("X2");
Response4Box = buffer[3].ToString("X2");
It worked well and gave me the answer i wanted. But now I have come across a twisted version of it in my c++ app..... Here is the code:
unsigned char buffer[8] = {};
char verString[64] = {};
m_msp430->WriteInternalCommand(cmd, 1, buffer);
m_msp430->ReadInternalCommand(cmd, 4, buffer);
sprintf(verString, "FPGA 0x42 Version (dd/mm/yyyy ID): %02d/%02d/20%02d %02d", ((buffer[3] & 0xF8) >> 3),
(buffer[2] & 0x0F), ((buffer[2] & 0xF0) >> 4), (buffer[3] & 0x07));
m_versionString->setText(String(verString), false);
Here m_versionString is a label and once this statement is executed, it prints e.g. FPGA 0x42 Version (dd/mm/yyyy ID): 00/00/2012 23
. I tried it in C# as follows:
// Description of VersionString label which displays
private string _VersionString;
public string VersionString
{
get
{
return _VersionString;
}
set
{
_VersionString = value;
OnPropertyChanged("VersionString");
}
}
public void GetVersion()
{
int cmd = 0x0A42;
Byte[] buffer = new Byte[8];
Byte[] verString = new Byte[64];
mComm.WriteInternalCommand(cmd, 1, ref buffer);
mComm.ReadInternalCommand(cmd, 4, ref buffer);
// Failing to figure out how to achieve it
VersionString = Convert.ToString(verString);
}
How can i perform these operations and display it on my VersionString?? :) Please help :)
Upvotes: 2
Views: 434
Reputation: 7951
Your C++ code is not equivalent to your C# code. You are masking and bit shifting each byte before your sprintf. There's no way that C# would know how to mask off the individual bytes to make your string.
Not much time right now.. but basically something like this..
verString = String.Format("FPGA 0x42 Version (dd/mm/yyyy ID): {0}/{1}/20{2} {3}", ((buffer[3] & 0xF8) >> 3),
(buffer[2] & 0x0F), ((buffer[2] & 0xF0) >> 4), (buffer[3] & 0x07));
or you can do it byte by byte without String.Format before calling convert
Upvotes: 2