Question

I'm translating some hardware communication code from VB6 to C#, and got a problem with som communication that need to send chars to the device. The VB6 Code looks like this:

Dim STARTQUEST As String
STARTQUEST = Chr(254) + Chr(address + 8) + Chr(address) + Chr(20) + Chr(128) + Chr(3)

And I have done this C# code

String m_startQuest = "";
m_startQuest = m_startQuest + (Char)254 + (Char)(address + 8) + (Char)address + (Char)20 + (Char)128 + (Char)3;

But I get the feel that I don't get the same output from them. Atleast in debug the STARTQUEST string looks alot different. Is there any other way to get the vb6 function to do the same in C#?

Was it helpful?

Solution

One option would be to add a reference to Microsoft.VisualBasic and use the Strings.Chr function

Chr is doing a lot more behind the scenes than you may realize (see the link).

OTHER TIPS

m_startQuest += Encoding.ASCII.GetString(
  new byte[] {254, address + 8, address, 28, 128, 3}
);

Why bytes? .Net char type supports Unicode and may be bigger than 255. SO it is safer to use bytes.

Update:

A runtime error in VB6

Dim s As String
s = Chr(1) + Chr(256)
Debug.Print s

Result is 257 in c#.

(((char)1) + ((char)256))

Result is a string in c#.

(((char)1) + "" + ((char)256))

a compile time error in c#.

Encoding.ASCII.GetString(
  new byte[] { 1, 256 }
);

Using the (Char) cast gets you the behaviour of VB6's ChrW (not Chr) function. VB6's Chr function does an ANSI<->Unicode conversion - to duplicate this in C# you can use System.Text.Encoding.Default.GetBytes().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top