问题描述
嗨亲爱的
我希望你身体健康。
拜托,帮助我
如果我有一个字符串,我想要转换为byte的数组但是任何元素如果它等于字符串中的一个char
又怎么能回去
例如
第一个函数:
输入:字符串值=78a52f693d57e8cb;
输出字节[] R = {0x7; 0x8; 0xa; 0x5; 0x2; 0xf; 0x6; 0x9; 0x3; 0xd; 0x5; 0x7; 0xe; 0x8; 0xc; 0xb};
第二功能:
输入字节[] R = {0x7; 0x8; 0xa; 0x5; 0x2; 0xf; 0x6; 0x9; 0x3; 0xd; 0x5; 0x7; 0xe; 0x8; 0xc; 0xb};
输出:字符串值=78a52f693d57e8cb;
认为所有
我尝试了什么:
第一个功能
Hi dear
I hope you are healthy and well.
please, help me
If I have a string and I want to convert to array of byte but any elements if its is equal one char in string
and how can go back
for example
first function:
input: string value= "78a52f693d57e8cb";
output byte[] R={0x7;0x8;0xa;0x5;0x2;0xf;0x6;0x9;0x3;0xd;0x5;0x7;0xe;0x8;0xc;0xb};
second function:
input byte[] R={0x7;0x8;0xa;0x5;0x2;0xf;0x6;0x9;0x3;0xd;0x5;0x7;0xe;0x8;0xc;0xb};
output: string value= "78a52f693d57e8cb";
thinks for all
What I have tried:
for first function
string Stemp = "0123456789ABCDEF";
byte[] Btemp = { 0x0, 0x1 , 0x2 , 0x3 , 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF};
byte[] R = new byte[value.Length];
foreach (char c in value)
{ R[z] = Btemp[Stemp.IndexOf(c)]; z = z + 1; }
第二个功能
for second function
char[] ty = new char[16];
for (int i = 0; i < 16; i++)
ty[i] = Stemp[Btemp.IndexOf(R[i])];
推荐答案
string value = "78a52f693d57e8cb";
byte[] R = new byte[value.Length];
int z = 0;
foreach (char c in value)
{
if (c >= '0' && c <= '9') R[z++] = (byte)(c - '0');
else if (c >= 'A' && c <= 'F') R[z++] = (byte)(c - 'A' + 10);
else if (c >= 'a' && c <= 'f') R[z++] = (byte)(c - 'a' + 10);
else throw new ArgumentException("Bad hex digit: " + c);
}
char[] ty = new char[R.Length];
for (int i = 0; i < R.Length; i++)
{
byte b = R[i];
if (b >= 0 && b <= 9) ty[i] = (char)(b + '0');
else if (b >= 10 && b <= 15) ty[i] = (char)(b - 10 + 'A');
else throw new ArgumentException("Bad hex digit: " + b);
}
string output = new string(ty);
// example
char [] c = { (char)48, (char)49, (char)50 };
String s = new string(c);
Console.WriteLine("First String : "+s);
这篇关于在字符串和字节之间转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!