如何从字符串重建原始BLOB值?

时间:2015-01-23 17:34:36

标签: c

这是一个将BLOB转换为字符串(例如X'1234')

的函数
static void output_hex_blob(FILE *out, const void *pBlob, int nBlob){
  int i;
  char *zBlob = (char *)pBlob;
  fprintf(out,"X'");
  for(i=0; i<nBlob; i++){ fprintf(out,"%02x",zBlob[i]&0xff); }
  fprintf(out,"'");
}

如何从字符串表示中重新构建BLOB值? 感谢名单!

1 个答案:

答案 0 :(得分:0)

尝试使用此功能

void *
blobToBytes(FILE *input)
{
    unsigned char *data;
    char           byte[3];
    unsigned int   size;
    unsigned int   index;

    if (input == NULL)
        return NULL;
    fseek(input, 0L, SEEK_END);
    size = ftell(input);
    rewind(input);

    byte[2] = '\0';
    if ((size - 3) % 2 != 0)
        return NULL;

    if ((fread(&byte, 1, 2, input) != 2) || (memcmp(byte, "X'", 2) != 0))
        return NULL;

    data = malloc((size - 3) / 2);
    if (data == NULL)
        return NULL;

    index = 0;
    while (fread(&byte, 1, 2, input) == 2)
        data[index++] = (unsigned char)strtol(byte, NULL, 16);

    return data;
}