2016-06-27 40 views
1

我将控制台程序的输入作为“Hai My Name是KrishNA”并将该字符串转换为ascii字符,并且得到的输出为543777096.我想如果我给相同数量的输入我想在同一个程序和空间的ASCII值与上述相同的输出是32,我想跳过space.I写的C#程序下面将字符串转换为ascii和ascii为字符串

string s1; 
s1 = Console.ReadLine(); 

byte[] bytes = Encoding.ASCII.GetBytes(s1); 
int result = BitConverter.ToInt32(bytes, 0); 
//foreach (int r in bytes) 
//{ 
Console.Write(result); 

//} 
//byte[] array = new byte[result]; 


byte[] buffer = System.Text.Encoding.UTF8.GetBytes(s1); 

foreach (int a in buffer) 
{ 
    Console.WriteLine(buffer); 
} 

请帮我在这

+0

所以你得到字符的前4个字节(“海”),放下其余的并将其转换为32位整数。你期望什么? – taffer

回答

1

试试这个

string s1; 
s1 = Console.ReadLine(); 

byte[] bytes = Encoding.ASCII.GetBytes(s1); 
int result = BitConverter.ToInt32(bytes, 0); 
Console.WriteLine(result); 

String decoded = Encoding.ASCII.GetString(bytes); 
Console.WriteLine("Decoded string: '{0}'", decoded); 
0

您不能将字符串转换为单个32位整数,在您的程序中,数字543777096代表“海”(包括空格),因此您无法将该数字转换回第一个字符串。使用循环将每个4个字符转换为Int32数字,因此您的字符串应该由Int32数字的数组表示。

0

你完全不清楚你使用int的结果。

如果要将数字打印到控制台(或文本文件),请改用字符串。

byte[] bytes = Encoding.ASCII.GetBytes(s1); 
string result = bytes.Aggregate("", (acc, b) => (acc.Length == 0 ? "" : acc + ", ") + b.ToString()); 
Console.WriteLine(result); 

// prints 72, 97, 105, 32, 98, 108, 97, 98, 108, 97 for "Hai blabla" 

如果你要离开的空间出来,可以过滤bytes

result = bytes 
     .Where(b => b != 32) 
     .Aggregate("", (acc, b) => (acc.Length == 0 ? "" : acc + ", ") + b.ToString()); 

对于较长的输入文字,你应该使用StringBuilder代替。