C#实现VB中的asc和chr函数,字符(含中文)转ASCII
/// <summary> /// 传入单个字符,得到字符的ASCII码 /// </summary> /// <param name="chr">汤</param> /// <returns>-13120</returns> public static int ASCII(string chr) { Encoding ecode = Encoding.GetEncoding("GB18030"); Byte[] codeBytes = ecode.GetBytes(chr); if (IsTwoBytesChar(chr)) { // 双字节码为高位乘256,再加低位 // 该为无符号码,再减65536 return (int)codeBytes[0] * 256 + (int)codeBytes[1] - 65536; } else { return (int)codeBytes[0]; } } /// <summary> /// 传入单个字符的ASCII码,得到ASCII码对应的字符(含双字节) /// </summary> /// <param name="asc">-13120</param> /// <returns>汤</returns> public static string Character(int asc) { //asc = asc + 65536; Encoding asciiEncoding = Encoding.GetEncoding("GB18030"); Byte[] chrByte = BitConverter.GetBytes((short)asc); string strCharacter = string.Empty; if (asc < 0 || asc > 255) { Byte[] chrByteStr = new byte[2]; chrByteStr[0] = chrByte[1]; chrByteStr[1] = chrByte[0]; strCharacter = asciiEncoding.GetString(chrByteStr); } else { Byte[] chrByteStr = new byte[1]; chrByteStr[0] = chrByte[0]; strCharacter = asciiEncoding.GetString(chrByteStr); } return (strCharacter); }
下面对应单元测试
[TestMethod] public void CharacterTest() { Assert.AreEqual(CommonFuntion.Character(-13120), "汤"); Assert.AreEqual(CommonFuntion.Character(-10544), "中"); } [TestMethod] public void ASCIITest() { Assert.AreEqual(CommonFuntion.ASCII("中"), -10544); Assert.AreEqual(CommonFuntion.ASCII("汤"), -13120); } [TestMethod] public void ASCIIAndCharTest() { Assert.AreEqual("中", CommonFuntion.Character(CommonFuntion.ASCII("中"))); Assert.AreEqual("汤", CommonFuntion.Character(CommonFuntion.ASCII("汤"))); Assert.AreEqual("A", CommonFuntion.Character(CommonFuntion.ASCII("A"))); Assert.AreEqual("¥", CommonFuntion.Character(CommonFuntion.ASCII("¥"))); Assert.AreEqual(-13120, CommonFuntion.ASCII(CommonFuntion.Character(-13120))); Assert.AreEqual(-10544, CommonFuntion.ASCII(CommonFuntion.Character(-10544))); }