private byte[] String2hex(string stmp)
{
StringBuilder sbtmp = new StringBuilder();
for (int i = 0; i < stmp.Length; i++)
{
if (stmp[i] >= ‘0‘ && stmp[i] <= ‘9‘)
{
sbtmp.Append(stmp[i]);
}
else if (stmp[i] >= ‘a‘ && stmp[i] <= ‘f‘)
{
sbtmp.Append(stmp[i]);
}
else if (stmp[i] >= ‘A‘ && stmp[i] <= ‘F‘)
{
sbtmp.Append(stmp[i]);
}
}
if (sbtmp.Length % 2 != 0)
sbtmp.Append(‘0‘);
byte[] btmp = new byte[sbtmp.Length/2];
byte l,h;
for (int i = 0,j = 2; i < sbtmp.Length;)
{
h = Char2hex(sbtmp[i]);
i++;
if(i >= sbtmp.Length)
break;
l = Char2hex(sbtmp[i]);
i++;
btmp[i-j] = (byte)(h*0x10+l);
j++;
}
return btmp;
}
private byte Char2hex(char s)
{
if (s >= ‘0‘ && s <= ‘9‘)
{
return (byte)(s - 0x30);
}
else if (s >= ‘a‘ && s <= ‘f‘)
{
return (byte)(s - 0x57);
}
else if (s >= ‘A‘ && s <= ‘F‘)
{
return (byte)(s - 0x37);
}
else
{
return 0;
}
}
c#学习(01)字符串转16进制