locked
Equivalent in C# of Asc & Chr functions of VB RRS feed

  • Question

  •  

    Although the subject of this post indicates it's a very simple problem but I'm having tough time in finding a solution.

     

    I'm having some old VB code which is using these functions to get ASCII Code of character (from 0-255) and same way getting the Char from Ascii code (from 0-255).

     

    I have created following functions to achieve the same in C# but it is not returning correct results. Value returned by the RetAsciiCode is coming in thousands instead of between 0-255.

     

    Equivalent values in VB are given below

     

    ? Asc(CurrentChar)

    226

    ? Asc(CurrentChar)

    139

    ? Asc(CurrentChar)

    204

     

    Pls help in solving this problem.

     

    public int RetAsciiCode(string MyString)

    {

    if (MyString.Length == 0)

    return 0;

    else if (MyString.Length > 1)

    MyString = MyString[0].ToString();

    int AsciiCodeO = (int)System.Convert.ToChar(MyString);

    byte[] AsciiCodeB = System.Text.Encoding.ASCII.GetBytes(MyString);

    //int AsciiCode = System.Convert.ToInt32(AsciiCodeB);

    return AsciiCodeO;

    }

     

    public string RetAsciiChar(int AsciiCode)

    {

    return System.Convert.ToChar(AsciiCode).ToString();

    }

    Thursday, March 27, 2008 6:48 PM

Answers

  • Finally, I have used reflector to disassemble the code and and for these two funcitons I have pasted the code in my class. I hope I'm not violating any of the copyright rules by doing that, if that is the case then I will remove that and add a reference to VB assembly.

     

    Reason for using this function is that this is a old program written in VB which translates a local non english font into unicode. Full code is written based on the ASCII code and after doing conversion everything was converted in c# except this asc and chr function.

    Friday, March 28, 2008 12:31 PM

All replies

  • The easiest thing to do would be to add the Microsoft.VisualBasic as a reference in your project.  Now you can use those commands in the context that might be most familiar to you.  Be sure to add a using statement to whatever file you need.

     

    using Microsoft.VisualBasic;

     

    public static int Asc(char String)

    Member of Microsoft.VisualBasic.Strings

    Summary:

    Returns an Integer value representing the character code corresponding to a character.

    Parameters:

    String: Required. Any valid Char or String expression. If String is a String expression, only the first character of the string is used for input. If String is Nothing or contains no characters, an System.ArgumentException error occurs.

    Return Values:

    Returns an Integer value representing the character code corresponding to a character.

     

    Code Snippet

    public static int StringToASCII(string input)

    {

    return Strings.Asc(input);

    }

     

    public static int CharToASCII(char input)

    {

    return Strings.Asc(input);

    }

     

    public static char ASCIIToString(int input)

    {

    return Strings.Chr(input)

    }

     

     

    Rudedog
    Thursday, March 27, 2008 6:59 PM
  •  

    I want to use this option as a last resort. Can't you suggest some c# equivalent instead of relying on VB lib.
    Thursday, March 27, 2008 7:21 PM
  • Characters in .NET are Unicode, not ASCII, so Unicode to ASCII conversion is an issue.

     

    If you want the exact result from Asc, then I suggest adding a reference to the VisualBasic assembly.

     

    Is there a reason why you want the translation from non ASCII characters to ASCII characters that Asc provides?

    Thursday, March 27, 2008 8:18 PM
  • Asc takes into account the code page of the system.  A codepage is used for translation of ANSI values.

     

    On a western code page Asc would operate in much the same way as System.Text.Encoding.GetDefault.GetBytes and returning the value of the first byte.  On DBCS code pages you Asc converts DBCS values that don't map to a single bytes, which will result in a 16-bit value.

     

    Asc does something like this:

    Code Snippet

    public static int Asc(char c)

    {

        int converted = c;

        if (converted >= 0x80)

        {

            byte[] buffer = new byte[2];

            // if the resulting conversion is 1 byte in length, just use the value

            if (System.Text.Encoding.Default.GetBytes(new char[] {c}, 0, 1, buffer, 0) == 1)

            {

                converted = buffer[0];

            }

            else

            {

                // byte swap bytes 1 and 2;

                converted = buffer[0] << 16 | buffer[1];

            }

        }

        return converted;

    }

     

     

    Thursday, March 27, 2008 8:50 PM
  • Finally, I have used reflector to disassemble the code and and for these two funcitons I have pasted the code in my class. I hope I'm not violating any of the copyright rules by doing that, if that is the case then I will remove that and add a reference to VB assembly.

     

    Reason for using this function is that this is a old program written in VB which translates a local non english font into unicode. Full code is written based on the ASCII code and after doing conversion everything was converted in c# except this asc and chr function.

    Friday, March 28, 2008 12:31 PM
  • The .NET 2.0 Framework license is a supplement to your Windows licence. All Windows licences that I've seen contain this clause:

    LIMITATION ON REVERSE ENGINEERING, DECOMPILATION, AND DISASSEMBLY. You may not

    reverse engineer, decompile, or disassemble the Product, except and only to the extent that it is expressly

    permitted by applicable law notwithstanding this limitation.

     

    So, yes, you're likely violating your license agreement.
    Friday, March 28, 2008 3:35 PM
  •  

    One more question in this same context. I'm licensed user of both VS2005 as well as VS2008. Although I have installed VS2008 but I was not able to play much with it. Previously I heard that Ms was going to release source code of net framework with VS2008.

     

    Is it supplied now with Vs 2008, kindly advs.

    Friday, March 28, 2008 5:01 PM
  •  Vinodonly wrote:

     

    One more question in this same context. I'm licensed user of both VS2005 as well as VS2008. Although I have installed VS2008 but I was not able to play much with it. Previously I heard that Ms was going to release source code of net framework with VS2008.

     

    Is it supplied now with Vs 2008, kindly advs.

    No, it's not included with VS2008.  VS2008 (with a hotfix) will access the symbols servers at Microsoft so you can debug some of the .NET Framework source.  See http://blogs.msdn.com/sburke/archive/2008/01/16/configuring-visual-studio-to-debug-net-framework-source-code.aspx for details on how to set it up.
    Friday, March 28, 2008 5:55 PM
  • Asc does something like this:

     

     

    Code Snippet

    public static int Asc(char c)

    {

        int converted = c;

        if (converted >= 0x80)

        {

            byte[] buffer = new byte[2];

            // if the resulting conversion is 1 byte in length, just use the value

            if (System.Text.Encoding.Default.GetBytes(new char[] {c}, 0, 1, buffer, 0) == 1)

            {

                converted = buffer[0];

            }

            else

            {

                // byte swap bytes 1 and 2;

                converted = buffer[0] << 16 | buffer[1];

            }

        }

        return converted;

    }

     

     

    Thanks for the code snippet. I did this to get a .NET string back from one ASCII char:
        static string Str(int t)
        {
          byte b = 0;
          b = Convert.ToByte(t); //throws overflow exception if t > maxbyte value
          return System.Text.ASCIIEncoding.UTF8.GetString(new byte[] { b });
        }
    

    Hope this is helpful to my fellow old C programmers out there (char is int type in C).
    Tuesday, May 19, 2009 5:14 PM
  • To convert a character to ASCII in csharp just cast that character as an int.  This should give you the ascii code for that character.

    char c = "s";
    int asc = (int)c;

    p.s. not sure if my syntax is correct, but the functionality should be.
    Monday, July 20, 2009 8:50 PM
  • Use the following in your C# code:

     

    1. using Microsoft.VisualBasic;

     

    Add the reference to Microsoft.VisualBasic.

    Use Strings.Asc(input) freely.

    Wednesday, September 1, 2010 12:32 AM
  • You don't need to reference the VB assemblies. The following has the same behavior as the VB6 functions.

    static short Asc(string String)
    {
      return Encoding.Default.GetBytes(String)[0];
    }
    static string Chr(int CharCode)
    {
      if (CharCode > 255)
        throw new ArgumentOutOfRangeException("CharCode", CharCode, "CharCode must be between 0 and 255.");
      return Encoding.Default.GetString(new[] { (byte)CharCode });
    }
    
    • Proposed as answer by Isidro Lopez Sunday, November 17, 2013 7:22 AM
    Wednesday, September 1, 2010 9:51 AM