我有组字节 
假设位 byte[] by = new byte[]{ 0x1d, 0x9b, 0x63, 0xc9, 0x33, 0xda, 0xe6, 0x62 };现在 有个字符串 string str = "1d9b63c933dae662";怎么样把这个字符串转换成和给定的by字节数组给定的值相同

解决方案 »

  1.   

    string getHexString(byte[] bytes)
    {
    char[] buff = new char[bytes.Length * 2];
    int p = 0;
    foreach(byte b in bytes)
    {
    buff[p++] = ToHexChar(b & 0x10);
    buff[p++] = ToHexChar(b % 0x10);
    }
    return new string(buff);
    }char ToHexChar(byte b)
    {
    return b < 10 ? '0' + b: 'A'+b-10;
    }
      

  2.   

      byte[] by = new byte[] { 0x1d, 0x9b, 0x63, 0xc9, 0x33, 0xda, 0xe6, 0x62 };
                byte[] by1 = new byte[8];
                string str= "1d9b63c933dae662";
                if (str.Length % 2 == 1||str.Length==0)
                    return;
                for (int i = 0; i < str.Length / 2; i++)
                {
                   by1[i]=(Byte)Convert.ToInt32(str.Substring(i*2, 2), 16);
                }
      

  3.   

    byte[] GetHexStringBytes(string str)
    {
    byte[] bytes = new bytes[str.length / 2];
    int p = 0;
    IEnumerator<char> ie = str.GetEnumerator();
    while(ie.MoveNext())
    {
    byte currentValue  = getValueFromHex(ie.Current);
    ie.MoveNext();
    byte nextValue = getValueFromHex(ie.Current);
    bytes[p++] = currentValue | 0x10 + nextValue;
    }
    return bytes;
    }
    byte getValueFromHex(char value)
    {
    return value >= 'A' : value - 'A' + 10 : value - '0';
    }
      

  4.   

    谢谢 liherun  原来Convert.ToInt32(,)第二个参数是这么用的   
      

  5.   

    Convert不是很好用的,Convert来Convert去很麻烦
      

  6.   

    'A' - 'A' = 0; 0 + 10 = 10 A转换成10
    'B' - 'A' = 1; 1 + 10 = 11 B转换成11