C#實(shí)現(xiàn)字符、ASCII碼和數(shù)字之間進(jìn)行轉(zhuǎn)換的方法大全
ASCII碼基礎(chǔ)
ASCII碼使用7位二進(jìn)制數(shù)(0-127)來(lái)表示128個(gè)字符,包括:
- 控制字符(0-31和127)
- 數(shù)字字符(48-57)
- 大寫(xiě)字母(65-90)
- 小寫(xiě)字母(97-122)
- 標(biāo)點(diǎn)符號(hào)和特殊字符
基本轉(zhuǎn)換方法
1. 字符與ASCII碼的相互轉(zhuǎn)換
using System;
class AsciiConverter
{
// 字符轉(zhuǎn)換為ASCII碼
public static int CharToAscii(char character)
{
return (int)character;
}
// ASCII碼轉(zhuǎn)換為字符
public static char AsciiToChar(int asciiCode)
{
// 確保ASCII碼在有效范圍內(nèi)
if (asciiCode >= 0 && asciiCode <= 127)
{
return (char)asciiCode;
}
else
{
throw new ArgumentOutOfRangeException("ASCII碼必須在0-127范圍內(nèi)");
}
}
// 使用示例
public static void DemonstrateBasicConversion()
{
// 字符轉(zhuǎn)ASCII
char letterA = 'A';
int asciiA = CharToAscii(letterA);
Console.WriteLine($"字符 '{letterA}' 的ASCII碼是: {asciiA}");
// ASCII轉(zhuǎn)字符
int asciiCode = 66;
char character = AsciiToChar(asciiCode);
Console.WriteLine($"ASCII碼 {asciiCode} 對(duì)應(yīng)的字符是: '{character}'");
// 數(shù)字字符的特殊處理
char digitChar = '7';
int digitAscii = CharToAscii(digitChar);
Console.WriteLine($"數(shù)字字符 '{digitChar}' 的ASCII碼是: {digitAscii}");
}
}2. 字符串與ASCII碼數(shù)組的轉(zhuǎn)換
public class StringAsciiConverter
{
// 字符串轉(zhuǎn)換為ASCII碼數(shù)組
public static int[] StringToAsciiArray(string text)
{
if (string.IsNullOrEmpty(text))
return new int[0];
int[] asciiArray = new int[text.Length];
for (int i = 0; i < text.Length; i++)
{
asciiArray[i] = (int)text[i];
}
return asciiArray;
}
// ASCII碼數(shù)組轉(zhuǎn)換為字符串
public static string AsciiArrayToString(int[] asciiArray)
{
if (asciiArray == null || asciiArray.Length == 0)
return string.Empty;
char[] charArray = new char[asciiArray.Length];
for (int i = 0; i < asciiArray.Length; i++)
{
if (asciiArray[i] < 0 || asciiArray[i] > 127)
{
throw new ArgumentException($"無(wú)效的ASCII碼: {asciiArray[i]}");
}
charArray[i] = (char)asciiArray[i];
}
return new string(charArray);
}
// 使用示例
public static void DemonstrateStringConversion()
{
string text = "Hello, ASCII!";
// 字符串轉(zhuǎn)ASCII數(shù)組
int[] asciiCodes = StringToAsciiArray(text);
Console.WriteLine($"字符串: {text}");
Console.WriteLine("ASCII碼數(shù)組: " + string.Join(", ", asciiCodes));
// ASCII數(shù)組轉(zhuǎn)字符串
string restoredText = AsciiArrayToString(asciiCodes);
Console.WriteLine($"還原后的字符串: {restoredText}");
}
}數(shù)字字符與數(shù)值的轉(zhuǎn)換
3. 數(shù)字字符與整數(shù)的轉(zhuǎn)換
public class DigitConverter
{
// 數(shù)字字符轉(zhuǎn)換為整數(shù)值
public static int CharToDigit(char digitChar)
{
if (char.IsDigit(digitChar))
{
// 方法1: 使用字符運(yùn)算
return digitChar - '0';
// 方法2: 使用int.Parse
// return int.Parse(digitChar.ToString());
}
else
{
throw new ArgumentException("輸入的字符不是數(shù)字字符");
}
}
// 整數(shù)轉(zhuǎn)換為數(shù)字字符
public static char DigitToChar(int digit)
{
if (digit >= 0 && digit <= 9)
{
// 方法1: 使用字符運(yùn)算
return (char)('0' + digit);
// 方法2: 使用字符轉(zhuǎn)換
// return digit.ToString()[0];
}
else
{
throw new ArgumentOutOfRangeException("數(shù)字必須在0-9范圍內(nèi)");
}
}
// 使用示例
public static void DemonstrateDigitConversion()
{
// 數(shù)字字符轉(zhuǎn)整數(shù)
char fiveChar = '5';
int fiveInt = CharToDigit(fiveChar);
Console.WriteLine($"字符 '{fiveChar}' 轉(zhuǎn)換為整數(shù): {fiveInt}");
Console.WriteLine($"類型: {fiveInt.GetType()}");
// 整數(shù)轉(zhuǎn)數(shù)字字符
int nineInt = 9;
char nineChar = DigitToChar(nineInt);
Console.WriteLine($"整數(shù) {nineInt} 轉(zhuǎn)換為字符: '{nineChar}'");
Console.WriteLine($"類型: {nineChar.GetType()}");
}
}高級(jí)轉(zhuǎn)換應(yīng)用
4. 十六進(jìn)制表示與ASCII的轉(zhuǎn)換
public class HexAsciiConverter
{
// ASCII碼轉(zhuǎn)換為十六進(jìn)制字符串
public static string AsciiToHex(char character)
{
int asciiCode = (int)character;
return asciiCode.ToString("X2"); // X2表示兩位十六進(jìn)制
}
// 十六進(jìn)制字符串轉(zhuǎn)換為ASCII字符
public static char HexToAscii(string hexString)
{
if (hexString.Length != 2)
throw new ArgumentException("十六進(jìn)制字符串必須是2位");
int asciiCode = Convert.ToInt32(hexString, 16);
return (char)asciiCode;
}
// 使用示例
public static void DemonstrateHexConversion()
{
char letter = 'Z';
string hex = AsciiToHex(letter);
Console.WriteLine($"字符 '{letter}' 的十六進(jìn)制ASCII表示: {hex}");
char restoredChar = HexToAscii(hex);
Console.WriteLine($"十六進(jìn)制 {hex} 還原為字符: '{restoredChar}'");
}
}5. 批量轉(zhuǎn)換和數(shù)據(jù)處理
public class BatchAsciiConverter
{
// 批量轉(zhuǎn)換字符串為ASCII碼列表
public static List<int> ConvertStringToAsciiList(string text)
{
return text.Select(c => (int)c).ToList();
}
// 過(guò)濾非ASCII字符
public static string FilterNonAsciiCharacters(string text)
{
return new string(text.Where(c => c <= 127).ToArray());
}
// 統(tǒng)計(jì)ASCII字符分布
public static Dictionary<char, int> AnalyzeAsciiDistribution(string text)
{
var distribution = new Dictionary<char, int>();
foreach (char c in text)
{
if (c <= 127) // 只統(tǒng)計(jì)ASCII字符
{
if (distribution.ContainsKey(c))
{
distribution[c]++;
}
else
{
distribution[c] = 1;
}
}
}
return distribution;
}
// 使用示例
public static void DemonstrateBatchOperations()
{
string sampleText = "Hello, World! 123";
// 批量轉(zhuǎn)換
List<int> asciiList = ConvertStringToAsciiList(sampleText);
Console.WriteLine("ASCII碼列表: " + string.Join(" ", asciiList));
// 字符分布分析
var distribution = AnalyzeAsciiDistribution(sampleText);
Console.WriteLine("字符分布:");
foreach (var pair in distribution.OrderBy(p => p.Key))
{
Console.WriteLine($"字符 '{(pair.Key == ' ' ? "空格" : pair.Key.ToString())}': 出現(xiàn){pair.Value}次");
}
}
}6. 實(shí)用工具類
public static class AsciiUtility
{
// 判斷字符是否為ASCII字符
public static bool IsAscii(char c)
{
return c <= 127;
}
// 判斷字符是否為數(shù)字字符
public static bool IsAsciiDigit(char c)
{
return c >= '0' && c <= '9';
}
// 判斷字符是否為字母
public static bool IsAsciiLetter(char c)
{
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
// 判斷字符是否為大寫(xiě)字母
public static bool IsAsciiUpper(char c)
{
return c >= 'A' && c <= 'Z';
}
// 判斷字符是否為小寫(xiě)字母
public static bool IsAsciiLower(char c)
{
return c >= 'a' && c <= 'z';
}
// 轉(zhuǎn)換為大寫(xiě)(僅對(duì)字母有效)
public static char ToAsciiUpper(char c)
{
if (IsAsciiLower(c))
{
return (char)(c - 32); // 小寫(xiě)轉(zhuǎn)大寫(xiě):ASCII碼減32
}
return c;
}
// 轉(zhuǎn)換為小寫(xiě)(僅對(duì)字母有效)
public static char ToAsciiLower(char c)
{
if (IsAsciiUpper(c))
{
return (char)(c + 32); // 大寫(xiě)轉(zhuǎn)小寫(xiě):ASCII碼加32
}
return c;
}
}實(shí)際應(yīng)用場(chǎng)景
7. 數(shù)據(jù)加密和解密示例
public class SimpleAsciiCipher
{
// 簡(jiǎn)單的ASCII加密(凱撒密碼變種)
public static string Encrypt(string text, int shift)
{
char[] result = new char[text.Length];
for (int i = 0; i < text.Length; i++)
{
if (AsciiUtility.IsAsciiLetter(text[i]))
{
char baseChar = AsciiUtility.IsAsciiUpper(text[i]) ? 'A' : 'a';
result[i] = (char)(((text[i] - baseChar + shift) % 26) + baseChar);
}
else
{
result[i] = text[i];
}
}
return new string(result);
}
// 解密
public static string Decrypt(string encryptedText, int shift)
{
return Encrypt(encryptedText, 26 - (shift % 26)); // 反向移位
}
// 使用示例
public static void DemonstrateEncryption()
{
string original = "Hello, World!";
int shift = 3;
string encrypted = Encrypt(original, shift);
string decrypted = Decrypt(encrypted, shift);
Console.WriteLine($"原文: {original}");
Console.WriteLine($"加密后: {encrypted}");
Console.WriteLine($"解密后: {decrypted}");
}
}性能優(yōu)化建議
- ??使用StringBuilder處理大量字符串操作??
- ??避免在循環(huán)中頻繁進(jìn)行類型轉(zhuǎn)換??
- ??使用預(yù)計(jì)算的值代替重復(fù)計(jì)算??
- ??考慮使用span和memory處理大文本?
// 高性能的ASCII處理示例
public static class HighPerformanceAscii
{
public static unsafe int[] StringToAsciiFast(string text)
{
int[] result = new int[text.Length];
fixed (char* pText = text)
{
for (int i = 0; i < text.Length; i++)
{
result[i] = pText[i];
}
}
return result;
}
}C#提供了多種靈活的方法來(lái)實(shí)現(xiàn)ASCII碼與數(shù)字之間的轉(zhuǎn)換。關(guān)鍵點(diǎn)包括:
- ??基本轉(zhuǎn)換??:使用強(qiáng)制類型轉(zhuǎn)換
(int)char和(char)int - ??數(shù)字字符處理??:注意數(shù)字字符'0'-'9'的ASCII碼是48-57
- ??邊界檢查??:始終驗(yàn)證ASCII碼的有效范圍(0-127)
- ??批量處理??:使用LINQ和數(shù)組操作提高效率
- ??實(shí)際應(yīng)用??:這些轉(zhuǎn)換在加密、數(shù)據(jù)處理、協(xié)議通信等領(lǐng)域非常有用
掌握這些轉(zhuǎn)換技巧可以幫助開(kāi)發(fā)者更好地處理文本數(shù)據(jù),理解字符編碼的本質(zhì),并在需要時(shí)實(shí)現(xiàn)高效的字符串處理算法。
以上就是C#實(shí)現(xiàn)字符、ASCII碼和數(shù)字之間進(jìn)行轉(zhuǎn)換的方法大全的詳細(xì)內(nèi)容,更多關(guān)于C#字符、ASCII碼與數(shù)字轉(zhuǎn)換的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
解析C#編程的通用結(jié)構(gòu)和程序書(shū)寫(xiě)格式規(guī)范
這篇文章主要介紹了C#編程的通用結(jié)構(gòu)和程序書(shū)寫(xiě)格式規(guī)范,這里我們根據(jù)C#語(yǔ)言的開(kāi)發(fā)方微軟給出的約定來(lái)作為編寫(xiě)樣式參照,需要的朋友可以參考下2016-01-01
python實(shí)現(xiàn)AutoResetEvent類的阻塞模式方法解析
AutoResetEvent :當(dāng)某個(gè)線程執(zhí)行到WaitOne()方法時(shí),該線程則會(huì)處于阻塞模式,當(dāng)被調(diào)用了Set()方法,阻塞的線程則會(huì)繼續(xù)向下執(zhí)行,其狀態(tài)立即被自動(dòng)設(shè)置為阻塞模式2012-11-11
C#開(kāi)發(fā)WinForm之DataGridView開(kāi)發(fā)詳解
這篇文章主要介紹了C#開(kāi)發(fā)WinForm之DataGridView開(kāi)發(fā)詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
C# LiteDB處理時(shí)間序列數(shù)據(jù)的高性能解決方案
LiteDB作為.NET生態(tài)下的輕量級(jí)嵌入式NoSQL數(shù)據(jù)庫(kù),一直是時(shí)間序列處理的優(yōu)選方案,本文將為大家大家簡(jiǎn)單介紹一下LiteDB處理時(shí)間序列數(shù)據(jù)的高性能解決方案,希望對(duì)大家有所幫助2025-08-08
Unity中的PostProcessScene實(shí)用案例深入解析
這篇文章主要為大家介紹了Unity中的PostProcessScene實(shí)用案例深入解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05
c#擴(kuò)展datatable轉(zhuǎn)json示例
這篇文章主要介紹了c#擴(kuò)展datatable轉(zhuǎn)json示例,需要的朋友可以參考下2014-05-05

