VB has a couple of native functions for converting a char to an ASCII value and vice versa - Asc() and Chr().
VB有一些本地函数,可以将一个字符转换为ASCII值,反之亦然——Asc()和Chr()。
Now I need to get the equivalent functionality in C#. What's the best way?
现在我需要在c#中获得等价的功能。最好的方法是什么?
7 个解决方案
#1
27
You could always add a reference to Microsoft.VisualBasic and then use the exact same methods: Strings.Chr and Strings.Asc.
你可以给微软添加一个参考。VisualBasic然后使用完全相同的方法:字符串。空空和Strings.Asc。
That's the easiest way to get the exact same functionality.
这是得到完全相同功能的最简单方法。
#2
18
For Asc()
you can cast the char
to an int
like this:
对于Asc(),可以将char类型转换成这样的int类型:
int i = (int)your_char;
and for Chr()
you can cast back to a char
from an int
like this:
对于Chr(),您可以从这样的int类型转换为char:
char c = (char)your_int;
Here is a small program that demonstrates the entire thing:
这里有一个小程序演示了整个事情:
using System;
class Program
{
static void Main()
{
char c = 'A';
int i = 65;
// both print "True"
Console.WriteLine(i == (int)c);
Console.WriteLine(c == (char)i);
}
}
#3
3
For Chr() you can use:
对于Chr()你可以使用:
char chr = (char)you_char_value;
#4
2
I got these using resharper, the exact code runs by VB on your machine
我使用resharper,用VB在你的机器上运行的代码。
/// <summary>
/// Returns the character associated with the specified character code.
/// </summary>
///
/// <returns>
/// Returns the character associated with the specified character code.
/// </returns>
/// <param name="CharCode">Required. An Integer expression representing the <paramref name="code point"/>, or character code, for the character.</param><exception cref="T:System.ArgumentException"><paramref name="CharCode"/> < 0 or > 255 for Chr.</exception><filterpriority>1</filterpriority>
public static char Chr(int CharCode)
{
if (CharCode < (int) short.MinValue || CharCode > (int) ushort.MaxValue)
throw new ArgumentException(Utils.GetResourceString("Argument_RangeTwoBytes1", new string[1]
{
"CharCode"
}));
if (CharCode >= 0 && CharCode <= (int) sbyte.MaxValue)
return Convert.ToChar(CharCode);
try
{
Encoding encoding = Encoding.GetEncoding(Utils.GetLocaleCodePage());
if (encoding.IsSingleByte && (CharCode < 0 || CharCode > (int) byte.MaxValue))
throw ExceptionUtils.VbMakeException(5);
char[] chars = new char[2];
byte[] bytes = new byte[2];
Decoder decoder = encoding.GetDecoder();
if (CharCode >= 0 && CharCode <= (int) byte.MaxValue)
{
bytes[0] = checked ((byte) (CharCode & (int) byte.MaxValue));
decoder.GetChars(bytes, 0, 1, chars, 0);
}
else
{
bytes[0] = checked ((byte) ((CharCode & 65280) >> 8));
bytes[1] = checked ((byte) (CharCode & (int) byte.MaxValue));
decoder.GetChars(bytes, 0, 2, chars, 0);
}
return chars[0];
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Returns an Integer value representing the character code corresponding to a character.
/// </summary>
///
/// <returns>
/// Returns an Integer value representing the character code corresponding to a character.
/// </returns>
/// <param name="String">Required. Any valid Char or String expression. If <paramref name="String"/> is a String expression, only the first character of the string is used for input. If <paramref name="String"/> is Nothing or contains no characters, an <see cref="T:System.ArgumentException"/> error occurs.</param><filterpriority>1</filterpriority>
public static int Asc(char String)
{
int num1 = Convert.ToInt32(String);
if (num1 < 128)
return num1;
try
{
Encoding fileIoEncoding = Utils.GetFileIOEncoding();
char[] chars = new char[1]
{
String
};
if (fileIoEncoding.IsSingleByte)
{
byte[] bytes = new byte[1];
fileIoEncoding.GetBytes(chars, 0, 1, bytes, 0);
return (int) bytes[0];
}
byte[] bytes1 = new byte[2];
if (fileIoEncoding.GetBytes(chars, 0, 1, bytes1, 0) == 1)
return (int) bytes1[0];
if (BitConverter.IsLittleEndian)
{
byte num2 = bytes1[0];
bytes1[0] = bytes1[1];
bytes1[1] = num2;
}
return (int) BitConverter.ToInt16(bytes1, 0);
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Returns an Integer value representing the character code corresponding to a character.
/// </summary>
///
/// <returns>
/// Returns an Integer value representing the character code corresponding to a character.
/// </returns>
/// <param name="String">Required. Any valid Char or String expression. If <paramref name="String"/> is a String expression, only the first character of the string is used for input. If <paramref name="String"/> is Nothing or contains no characters, an <see cref="T:System.ArgumentException"/> error occurs.</param><filterpriority>1</filterpriority>
public static int Asc(string String)
{
if (String == null || String.Length == 0)
throw new ArgumentException(Utils.GetResourceString("Argument_LengthGTZero1", new string[1]
{
"String"
}));
return Strings.Asc(String[0]);
}
Resources are just stored error message, so somehow the way you want ignore them, and the other two method which you do not have access to are as follow:
资源只是存储错误消息,所以您想要忽略它们的方式,以及您无法访问的其他两种方法如下:
internal static Encoding GetFileIOEncoding()
{
return Encoding.Default;
}
internal static int GetLocaleCodePage()
{
return Thread.CurrentThread.CurrentCulture.TextInfo.ANSICodePage;
}
#5
0
Strings.Asc is not equivalent with a plain C# cast for non ASCII chars that can go beyond 127 code value. The answer I found on https://social.msdn.microsoft.com/Forums/vstudio/en-US/13fec271-9a97-4b71-ab28-4911ff3ecca0/equivalent-in-c-of-asc-chr-functions-of-vb?forum=csharpgeneral amounts to something like this:
字符串。Asc与非ASCII字符的普通c#转换不一样,它可以超过127个代码值。我在https://social.msdn.microsoft.com/forums/vstudio/vstudio/13fec271 -9a97-4b71-ab28- 4911ff3ecca0/- in-c-of- c-of- c-of- of- c-of- of- c-of- of- c-of- of- c-of- c-of- c-of- of- c-of- c-of- of- c-of- of- c-of- c-of- c-of- c-of- c-of- c-of- c-论坛=csharpgeneral相当于这样:
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;
}
Or, if you want the read deal add a reference to Microsoft.VisualBasic assembly.
或者,如果你想让阅读协议添加一个关于微软的参考。VisualBasic组装。
#6
0
//Char to Int - ASC("]")
int lIntAsc = (int)Char.Parse("]");
Console.WriteLine(lIntAsc); //Return 91
//Int to Char
char lChrChar = (char)91;
Console.WriteLine(lChrChar ); //Return "]"
#7
0
Given char c and int i, and functions fi(int) and fc(char):
给定char c和int i,以及函数fi(int)和fc(char):
From char to int (analog of VB Asc()): explicitly cast the char as an int: int i = (int)c;
从char到int(类似于VB Asc()):显式地将char类型转换为int: int i = (int)c;
or implicitly cast (promote): fi(char c) {i+= c;}
或隐式cast(提升):fi(char c) {i+= c;}
From int to char (analog of VB Chr()):
从int到char(模拟VB Chr()):
explicitly cast the int as an char: char c = (char)i, fc(int i) {(char)i};
显式地将int转换为char: char c = (char)i、fc(int i) {(char)i};
An implicit cast is disallowed, as an int is wider (has a greater range of values) than a char
隐式转换是不允许的,因为int比char更宽(有更大范围的值)。
#1
27
You could always add a reference to Microsoft.VisualBasic and then use the exact same methods: Strings.Chr and Strings.Asc.
你可以给微软添加一个参考。VisualBasic然后使用完全相同的方法:字符串。空空和Strings.Asc。
That's the easiest way to get the exact same functionality.
这是得到完全相同功能的最简单方法。
#2
18
For Asc()
you can cast the char
to an int
like this:
对于Asc(),可以将char类型转换成这样的int类型:
int i = (int)your_char;
and for Chr()
you can cast back to a char
from an int
like this:
对于Chr(),您可以从这样的int类型转换为char:
char c = (char)your_int;
Here is a small program that demonstrates the entire thing:
这里有一个小程序演示了整个事情:
using System;
class Program
{
static void Main()
{
char c = 'A';
int i = 65;
// both print "True"
Console.WriteLine(i == (int)c);
Console.WriteLine(c == (char)i);
}
}
#3
3
For Chr() you can use:
对于Chr()你可以使用:
char chr = (char)you_char_value;
#4
2
I got these using resharper, the exact code runs by VB on your machine
我使用resharper,用VB在你的机器上运行的代码。
/// <summary>
/// Returns the character associated with the specified character code.
/// </summary>
///
/// <returns>
/// Returns the character associated with the specified character code.
/// </returns>
/// <param name="CharCode">Required. An Integer expression representing the <paramref name="code point"/>, or character code, for the character.</param><exception cref="T:System.ArgumentException"><paramref name="CharCode"/> < 0 or > 255 for Chr.</exception><filterpriority>1</filterpriority>
public static char Chr(int CharCode)
{
if (CharCode < (int) short.MinValue || CharCode > (int) ushort.MaxValue)
throw new ArgumentException(Utils.GetResourceString("Argument_RangeTwoBytes1", new string[1]
{
"CharCode"
}));
if (CharCode >= 0 && CharCode <= (int) sbyte.MaxValue)
return Convert.ToChar(CharCode);
try
{
Encoding encoding = Encoding.GetEncoding(Utils.GetLocaleCodePage());
if (encoding.IsSingleByte && (CharCode < 0 || CharCode > (int) byte.MaxValue))
throw ExceptionUtils.VbMakeException(5);
char[] chars = new char[2];
byte[] bytes = new byte[2];
Decoder decoder = encoding.GetDecoder();
if (CharCode >= 0 && CharCode <= (int) byte.MaxValue)
{
bytes[0] = checked ((byte) (CharCode & (int) byte.MaxValue));
decoder.GetChars(bytes, 0, 1, chars, 0);
}
else
{
bytes[0] = checked ((byte) ((CharCode & 65280) >> 8));
bytes[1] = checked ((byte) (CharCode & (int) byte.MaxValue));
decoder.GetChars(bytes, 0, 2, chars, 0);
}
return chars[0];
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Returns an Integer value representing the character code corresponding to a character.
/// </summary>
///
/// <returns>
/// Returns an Integer value representing the character code corresponding to a character.
/// </returns>
/// <param name="String">Required. Any valid Char or String expression. If <paramref name="String"/> is a String expression, only the first character of the string is used for input. If <paramref name="String"/> is Nothing or contains no characters, an <see cref="T:System.ArgumentException"/> error occurs.</param><filterpriority>1</filterpriority>
public static int Asc(char String)
{
int num1 = Convert.ToInt32(String);
if (num1 < 128)
return num1;
try
{
Encoding fileIoEncoding = Utils.GetFileIOEncoding();
char[] chars = new char[1]
{
String
};
if (fileIoEncoding.IsSingleByte)
{
byte[] bytes = new byte[1];
fileIoEncoding.GetBytes(chars, 0, 1, bytes, 0);
return (int) bytes[0];
}
byte[] bytes1 = new byte[2];
if (fileIoEncoding.GetBytes(chars, 0, 1, bytes1, 0) == 1)
return (int) bytes1[0];
if (BitConverter.IsLittleEndian)
{
byte num2 = bytes1[0];
bytes1[0] = bytes1[1];
bytes1[1] = num2;
}
return (int) BitConverter.ToInt16(bytes1, 0);
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Returns an Integer value representing the character code corresponding to a character.
/// </summary>
///
/// <returns>
/// Returns an Integer value representing the character code corresponding to a character.
/// </returns>
/// <param name="String">Required. Any valid Char or String expression. If <paramref name="String"/> is a String expression, only the first character of the string is used for input. If <paramref name="String"/> is Nothing or contains no characters, an <see cref="T:System.ArgumentException"/> error occurs.</param><filterpriority>1</filterpriority>
public static int Asc(string String)
{
if (String == null || String.Length == 0)
throw new ArgumentException(Utils.GetResourceString("Argument_LengthGTZero1", new string[1]
{
"String"
}));
return Strings.Asc(String[0]);
}
Resources are just stored error message, so somehow the way you want ignore them, and the other two method which you do not have access to are as follow:
资源只是存储错误消息,所以您想要忽略它们的方式,以及您无法访问的其他两种方法如下:
internal static Encoding GetFileIOEncoding()
{
return Encoding.Default;
}
internal static int GetLocaleCodePage()
{
return Thread.CurrentThread.CurrentCulture.TextInfo.ANSICodePage;
}
#5
0
Strings.Asc is not equivalent with a plain C# cast for non ASCII chars that can go beyond 127 code value. The answer I found on https://social.msdn.microsoft.com/Forums/vstudio/en-US/13fec271-9a97-4b71-ab28-4911ff3ecca0/equivalent-in-c-of-asc-chr-functions-of-vb?forum=csharpgeneral amounts to something like this:
字符串。Asc与非ASCII字符的普通c#转换不一样,它可以超过127个代码值。我在https://social.msdn.microsoft.com/forums/vstudio/vstudio/13fec271 -9a97-4b71-ab28- 4911ff3ecca0/- in-c-of- c-of- c-of- of- c-of- of- c-of- of- c-of- of- c-of- c-of- c-of- of- c-of- c-of- of- c-of- of- c-of- c-of- c-of- c-of- c-of- c-of- c-论坛=csharpgeneral相当于这样:
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;
}
Or, if you want the read deal add a reference to Microsoft.VisualBasic assembly.
或者,如果你想让阅读协议添加一个关于微软的参考。VisualBasic组装。
#6
0
//Char to Int - ASC("]")
int lIntAsc = (int)Char.Parse("]");
Console.WriteLine(lIntAsc); //Return 91
//Int to Char
char lChrChar = (char)91;
Console.WriteLine(lChrChar ); //Return "]"
#7
0
Given char c and int i, and functions fi(int) and fc(char):
给定char c和int i,以及函数fi(int)和fc(char):
From char to int (analog of VB Asc()): explicitly cast the char as an int: int i = (int)c;
从char到int(类似于VB Asc()):显式地将char类型转换为int: int i = (int)c;
or implicitly cast (promote): fi(char c) {i+= c;}
或隐式cast(提升):fi(char c) {i+= c;}
From int to char (analog of VB Chr()):
从int到char(模拟VB Chr()):
explicitly cast the int as an char: char c = (char)i, fc(int i) {(char)i};
显式地将int转换为char: char c = (char)i、fc(int i) {(char)i};
An implicit cast is disallowed, as an int is wider (has a greater range of values) than a char
隐式转换是不允许的,因为int比char更宽(有更大范围的值)。