Hello,
I am trying to translate my Visual Basic program to C#.
Right now i am have having problems translating this code
[CODE]Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
inchar = SerialPort1.ReadLine
IDstr = Microsoft.VisualBasic.Left(inchar, 2)
Datastr = Microsoft.VisualBasic.Right(inchar, 6)
result = Val("&h" & Datastr)
''Energy = (result * 38) / 1000
End Sub[/CODE]
I'd like to know how to make my IDstr read the most left 2 bits, and Datastr read the right most 6 bits.
For now i have this:
[CODE]private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
string inchar, IDstr, Datastr;
inchar = SerialPort1.ReadLine();
IDstr = Microsoft.VisualBasic.Left(inchar, 2); // need help translating this line
Datastr = Microsoft.VisualBasic.Right(inchar, 6); // need help translating this line
result = Val("&h" & Datastr);
/*''Energy = (result * 38) / 1000;*/
}[/CODE]
Thank you!
Loading
VulpesPosted Oct 4, 2011, 6:56 AM
result = Convert.ToInt32(Datastr, 16);
Incidentally, you're opening post - when you were talking about 'bits' - sounded like you were expecting a binary rather than a hexadecimal string?
If that's the case, then change '16' in the above line to '2'.
Gary SohPosted Oct 4, 2011, 5:23 AM
{
string inchar = string.Empty;
string IDstr = string.Empty;
string Datastr = string.Empty;
int result ;
inchar = SerialPort1.ReadLine();
IDstr = inchar.Substring(0, 2);
Datastr = inchar.Substring(inchar.Length - 6);
result = Convert.ToUInt32(Datastr, 16);
/*''Energy = (result * 38) / 1000;*/
}
there an new error on that line after replacing it.
"cannot implicitly convert type 'uint' to 'int'. An explicit conversion exists(are you missing a cast?)
VulpesPosted Oct 4, 2011, 5:06 AM
Gary SohPosted Oct 4, 2011, 4:48 AM
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
string inchar = string.Empty;
string IDstr = string.Empty;
string Datastr = string.Empty;
Int32 result;
inchar = SerialPort1.ReadLine();
IDstr = inchar.Substring(0, 2);
Datastr = inchar.Substring(inchar.Length - 7);
result = Val("&h" & Datastr);
/*''Energy = (result * 38) / 1000;*/
}
about the result = Val("&h" & Datastr);
I have a problem with Val, how do i fix it?
VulpesPosted Oct 4, 2011, 4:35 AM
int len = inchar.Length;
if (len >= 2)
IDstr = inchar.Substring(0,2);
else
IDstr = inchar;
if (len >= 6)
Datastr = inchar.Substring(len - 6);
else
Datastr = inchar;
// 'result' assumed to be an int defined elsewhere
result = Convert.ToInt32(Datastr, 16);