【问题标题】:convert uint8_t array to char array in c在c中将uint8_t数组转换为char数组
【发布时间】:2012-04-29 10:03:22
【问题描述】:

最初我想将此uint8_t 数组转换为c 中的char 数组。我一直在尝试解决这个问题。我的第一个替代解决方案是将另一个类型值复制到临时值,将 tmp 值复制到可写字符,然后从内存中删除 tmp 值。顺便说一句,这用于伴随 blake 散列函数。这是我的代码 sn-p:

char * bl(char *input)
{
    uint8_t  output[64];
    char msg[]= "";
    char *tmp;

    int dInt;

    memset(output,0,64);
    tmp = (char*) malloc(64);
    if (!tmp){
            exit( 1);
    }

    dInt = strlen(input);

    if (dInt > 0xffff){
            exit( 1);
    }
    uint8_t data[dInt];

    memset(data,0, dInt);
    strlcpy(data,input,dInt);
    uint64_t dLen =dInt;
    blake512_hash(output, data,dLen);

    int k;
    for (k=0;k<64;k++){
            tmp[k] = output[k];  //does this "copy" is buggy code?
    }

    memcpy(msg, tmp,64);
    //so here I can to delete tmp value
    // I dont want there were left unused value in memory
    // delete tmp;  
    free(tmp);

    return  msg;
}

我认为上面的代码仍然没有效率,那么您有什么意见、提示和修复? 之前非常感谢!

【问题讨论】:

    标签: c arrays hash


    【解决方案1】:

    首先,您永远不应该返回指向局部变量的指针,因为该变量将在函数退出时被销毁。您可能希望将输出数组传递给bl 函数并使用它来输出字符串。

    对于大多数情况(如果 uint8_t 是字符,通常是这种情况),memcpy(msg, output, 64) 应该足够了。如果您想对此严格要求(坦率地说,blake512_hash 不应该首先返回uint8_t 数组,如果您一直期望char 数组作为输出),您可以简单地调用msg[k] = (char)tmp[k]您的 for 循环并删除 memcpy

    【讨论】:

    • 我想稍后使用这个函数在 Python 中调用,我希望这个函数稍后会返回一个字符串值。
    • @user1309539 是的,但您仍然应该解决我在回答中提到的问题。您根本无法将指针返回到局部变量。
    • 那么 tmp 变量就没有用了。从 tmp 变量中复制什么,因为 tmp 变量只分配了字符而不是输出?
    • @user1309539 你不需要 tmp 变量,因为你可以简单地将输出复制到msg
    【解决方案2】:

    这里有点不对。

    dInt = strlen(input) + 1; // dInt is the size of the string including the terminating '\0'.
    

    strlcpy 确实使用了大小,而不是 strlen。

    味精 = tmp;而不是释放 tmp。因为 msg 是 const char* "" (用 C++ 术语)。

    【讨论】:

    • 嗯,是的,谢谢。又错了,请对上述代码提出您的建议,谢谢:)
    猜你喜欢
    • 2019-10-14
    • 1970-01-01
    • 2019-11-21
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    • 2016-04-07
    • 1970-01-01
    相关资源
    最近更新 更多