我有一个字符串,我将其更改为十六进制值,所以我想将它们存储在字节数组中,但它给出了“输入字符串格式不正确”的错误。这是我的代码:
byte[] PlainText = new byte[16];
byte[] MasterKey = new byte[16];
string input = "Hello";
char[] values = input.ToCharArray();
int i =0;
foreach (char letter in values)
{
int value = Convert.ToInt32(letter);
string hexout = String.Format("{0:X}", value);
PlainText[i++] = Convert.ToByte(hexout);
}
答案 0 :(得分:1)
更改初始代码
byte[] PlainText = new byte[16];
byte[] MasterKey = new byte[16];
string input = "Hello";
char[] values = input.ToCharArray();
int i =0;
string hexout=string.empty;
foreach (char letter in values)
{
int value = Convert.ToInt32(letter);
hexout+= String.Format("{0:X}", value);
}
plaintext=StringToByteArray(hexout);
用于将十六进制转换为字节数组
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
或
用于解析长字符串
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length/2;
byte[] bytes = new byte[NumberChars];
using (var sr = new StringReader(hex))
{
for (int i = 0; i < NumberChars; i++)
bytes[i] =
Convert.ToByte(new string(new char[2]{(char)sr.Read(), (char)sr.Read()}), 16);
}
return bytes;
}
答案 1 :(得分:0)
var bytes=System.Text.Encoding.UTF8.GetBytes(yourString);