这两天要开发一个软件,需要把四位十六进制字符(byte)/字符串(string),转换为十进制数组,
大概这样的画风:byte[] Hex = {0xEF,0xDA}
最后出来是这样的,方法有些笨,但是还能用
public static byte[] hexStringToByte(string hexStr)
{
int len = (hexStr.Length / 2);
byte[] result = new byte[len];
char[] achar = hexStr.ToCharArray();
for (int i = 0; i < len; i++)
{
int pos = i * 2;
int value = Convert.ToInt32(String.Format("{0:X}", achar[pos]), 16);
int value1 = Convert.ToInt32(String.Format("{0:X}", achar[pos + 1]), 16);
result[i] = (byte)((Convert.ToByte(value) << 4) | (Convert.ToByte(value1)));
}
return result;
}
然后是,int转换成16进制字符数组:
private byte[] intToBytes4(int n)
{
byte[] data = new byte[4];
int nn = Convert.ToInt32(n);
int low = nn & 0xffff;
int high = nn >> 16;
for (int i = 0; i < 4; i++)
{
data[0] = (byte)(high >> 8);
data[1] = (byte)(high & 0x00FF);
data[2] = (byte)(low >> 8);
data[3] = (byte)(low & 0x00FF);
}
return data;
}
private byte[] intToBytes2(int n)
{
int num = n & 0x0000FFFF;
byte[] b = new byte[2];
b[0] = (byte)(num >> 8);
b[1] = (byte)(num & 0x00FF);
return b;
}