我试图将字符串的值放入字节数组而不更改字符.这是因为字符串实际上是数据的字节表示.
目标是将输入字符串移动到字节数组中,然后使用以下命令转换字节数组:
string result = System.Text.Encoding.UTF8.GetString(data);
Run Code Online (Sandbox Code Playgroud)
我希望有人可以帮助我,虽然我知道这不是一个很好的描述.
编辑:也许我应该解释一下,我正在研究的是一个带有文本框的简单窗体,用户可以将编码数据复制到其中,然后单击预览以查看解码数据.
编辑:多一点代码:(inputText是一个文本框)
private void button1_Click(object sender, EventArgs e)
{
string inputString = this.inputText.Text;
byte[] input = new byte[inputString.Length];
for (int i = 0; i < inputString.Length; i++)
{
input[i] = inputString[i];
}
string output = base64Decode(input);
this.inputText.Text = "";
this.inputText.Text = output;
}
Run Code Online (Sandbox Code Playgroud)
这是Windows窗体的一部分,它包含一个富文本框.这段代码不起作用,因为它不会让我将char类型转换为byte.但是,如果我将线路更改为:
private void button1_Click(object sender, EventArgs e)
{
string inputString = this.inputText.Text;
byte[] input = new byte[inputString.Length];
for (int i = 0; i < inputString.Length; i++)
{
input[i] = (byte)inputString[i];
}
string output = base64Decode(input);
this.inputText.Text = "";
this.inputText.Text = output;
}
Run Code Online (Sandbox Code Playgroud)
它编码的价值,我不希望这样.我希望这能更好地解释我想要做的事情.
编辑:base64Decode函数:
public string base64Decode(byte[] data)
{
try
{
string result = System.Text.Encoding.UTF8.GetString(data);
return result;
}
catch (Exception e)
{
throw new Exception("Error in base64Decode" + e.Message);
}
}
Run Code Online (Sandbox Code Playgroud)
为了清楚起见,不使用base64对字符串进行编码.这只是我的错误命名.
请注意,这只是一行输入.
我懂了.问题是我总是试图解码错误的格式.我觉得非常愚蠢,因为当我发布示例输入时,我看到它必须是十六进制,从那时起就很容易了.我用这个网站作为参考:http: //msdn.microsoft.com/en-us/library/bb311038.aspx
我的代码:
public string[] getHexValues(string s)
{
int j = 0;
string[] hex = new String[s.Length/2];
for (int i = 0; i < s.Length-2; i += 2)
{
string temp = s.Substring(i, 2);
this.inputText.Text = temp;
if (temp.Equals("0x")) ;
else
{
hex[j] = temp;
j++;
}
}
return hex;
}
public string convertFromHex(string[] hex)
{
string result = null;
for (int i = 0; i < hex.Length; i++)
{
int value = Convert.ToInt32(hex[i], 16);
result += Char.ConvertFromUtf32(value);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
我现在觉得很蠢,但感谢所有帮助过的人,特别是@Jon Skeet.
你是说你有这样的事情:
string s = "48656c6c6f2c20776f726c6421";
Run Code Online (Sandbox Code Playgroud)
你想要这些值作为字节数组?然后:
public IEnumerable<byte> GetBytesFromByteString(string s) {
for (int index = 0; index < s.Length; index += 2) {
yield return Convert.ToByte(s.Substring(index, 2), 16);
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
string s = "48656c6c6f2c20776f726c6421";
var bytes = GetBytesFromByteString(s).ToArray();
Run Code Online (Sandbox Code Playgroud)
注意输出
Console.WriteLine(System.Text.ASCIIEncoding.ASCII.GetString(bytes));
Run Code Online (Sandbox Code Playgroud)
是
Hello, world!
Run Code Online (Sandbox Code Playgroud)
你显然需要使上述方法更安全.