Hex String to Byte Array

解决方案 »

  1.   

    BYTE buf[100] 
    buf=(BYTE*)(LPCTSTR)CStringVar
      

  2.   

    我说的CStringVar 是16进制的String,比如1A 08 3E 4F......
    我想不可以这样做吧?
      

  3.   

    那就先用
    这个函数我好象没有看到过,只能自己写了!我很早写过类似这个功能的代码先转化成 char* , 并得到长度 nLen;BYTE* btResult = new BYTE[nLen/2];
    BYTE n[3];
    for(j=0; j<nLen/2*2; j++)
    {
      if(strRec[j]==' ')
      {
        n[0]=0;
        j++;
      }
      else
         n[0]=strRec[j++]-48;
      n[1]=strRec[j]-48;
      n[2]=n[0]*16+n[1];
      }
      btResult[j] = n[2];
    }
    放到你的程序里面去试试看!
      

  4.   

    空格的意思就是 当出现 1A , _B,就是只有一个B,前面应该有一个空格,如果你没有空格那就没有办法转换了!
      

  5.   

    CByteArray byArray;
    BYTE* pByteBuf = new BYTE[cNum];// 在pByteBuf里填入1A 08 3E 4F......
    // ....// 下面做CByteArray的转换byArray.SetSize(cNum);
    memcpy(byArray.GetData(), pByteBuf, cNum * sizeof(BYTE)); 
     
      

  6.   

    n[0]=strRec[j++]-48;
      n[1]=strRec[j]-48;
      
      感谢您的回答!!!  减48 是什么意思?您能解释一下吗?
      

  7.   

    48是什么, '0'的ASCII码值。字符串本身都是ASCII码值,要想得到真正数值必须减去48,但原程序不直观n[0]=strRec[j++]-'0';
      n[1]=strRec[j]-'0';这样就好懂了吧!
      
      

  8.   


    //假设十六进制串是两个代表一个字节
    CByteArray byArray;
    BYTE tem;
    for(j=0; j<nLen; j++)
    {
      // skip the space
      if (strRec[j]==' ')
        j++;  if (j >= nLen)
        break;
      else
         tem = strRec[j ++] - '0';
      if (j < nLen)
         tem = tem * 16 + (strRec[j]- '0');
      byArray.Add(tem);
    }byArray.GetSize()是 Byte Array的长度
    byArray[i]用于访问具体的字节
      

  9.   

    原来的for(j=0; j<nLen/2*2; j++)方式会导致 btResult溢出
    BYTE* btResult = new BYTE[nLen/2];还是改成这样好:// CString strVal = "1A 08 3E 4F......";;long nLen = strVal.GetLength();
    //假设十六进制串是两个代表一个字节
    CByteArray byArray;
    BYTE tem;
    long j;
    for(j=0; j < nLen; j++)
    {
      // skip the space
      while (strVal[j]==' ' && j < nLen)
        j++;  if (j >= nLen)
        break;
      else
         tem = strVal[j ++] - '0';
      if (j < nLen && strVal[j] != ' ')
         tem = tem * 16 + (strVal[j]- '0');
      byArray.Add(tem);
    }byArray.GetSize()是 Byte Array的长度
    byArray[i]用于访问具体的字节
      

  10.   

    虽然不太正确,我还是给分了
    问题出在char >9 时出错