日期:2014-05-18  浏览次数:21417 次

无法将类型"byte[]"隐式转换为"byte"!!!

//16进制格式的string 转成byte[]
  public static byte[] GetBytes(string hexString, out int discarded)
  {
  discarded = 0;
  string newString = "";
  char c;
  // remove all none A-F, 0-9, characters
  for (int i = 0; i < hexString.Length; i++)
  {
  c = hexString[i];
  if (Uri.IsHexDigit(c))
  newString += c;
  else
  discarded++;
  }
  // if odd number of characters, discard last character
  if (newString.Length % 2 != 0)
  {
  discarded++;
  newString = newString.Substring(0, newString.Length - 1);
  }

  int byteLength = newString.Length / 2;
  byte[] bytes = new byte[byteLength];


  string hex;
  int j = 0;
  for (int i = 0; i < bytes.Length; i++)
  {
  hex = new String(new Char[] { newString[j], newString[j + 1] });


  bytes[i] = HexToByte(hex); //此处提示 无法将类型"byte[]"隐式转换为"byte"!!!
  j = j + 2;
  }
  return bytes;
  }


  private static byte[] HexToByte(string hexString)
  {
  byte[] returnBytes = new byte[hexString.Length / 2];
  for (int i = 0; i < returnBytes.Length; i++)
  returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
  return returnBytes;
  } 



在线等。

------解决方案--------------------
错误提示已经很清楚了

------解决方案--------------------
HexToByte返回的是 byte数组,而bytes[i]这是一个byte类型,完全不对应
------解决方案--------------------
bytes[i] = HexToByte(hex);
=>
bytes[i] = HexToByte(hex[0]);
------解决方案--------------------
bytes[i] = HexToByte(hex);
=>
bytes[i] = HexToByte()[0];
------解决方案--------------------
C# code

//bytes[i] = HexToByte(hex);
bytes[i] = HexToByte(hex)[0];

------解决方案--------------------
int x = 0;
GetBytes(string hexString, out x);
x 为你要的值。