将 unsigned char(数组)转换为 unsigned int(数组)

标签 c arrays

我想创建一个函数,将 unsigned char 转换为 unsigned int 并将其存储到数组中。然而,这最终会出现一个错误,显示

passing argument 1 of 'sprintf' from incompatible pointer type.

int main(void) {
    unsigned char key[16] = "1234567812345678";
    phex(key, 16); //store into an array here
}

uint64_t* phex(unsigned char* string, long len)
{
    uint64_t hex[len];
    int count = 0;

    for(int i = 0; i < len; ++i) {
        count = i * 2;
        sprintf(hex + count, "%.2x", string[i]);
    }

    for(int i = 0; i < 32; i++)
        printf(hex[i]);

    return hex;
}

最佳答案

正如评论已经说过的,你的代码有问题...... 首先, sprintf 函数所做的事情与您想要/期望它做的事情完全相反。接下来,在函数中创建一个局部变量,并返回指向它的指针。函数退出后,指针就无效。我看到的第三个问题是你永远不会为任何东西分配返回值......

关于如何修复代码的建议:

unsigned* phex(unsigned char* string, long len);

int main(void) {
    int i;
    unsigned char key[16] = "1234567812345678";

    unsigned* ints = phex(key,16); //store into an array here

    for(i = 0; i < 16; i++)
        printf("%d ", ints[i]);

    //never forget to deallocate memory
    free(ints);

    return 0;
}

unsigned* phex(unsigned char* string, long len)
{
    int i;
    //allocate memory for your array
    unsigned* hex = (unsigned*)malloc(sizeof(unsigned) * len);

    for(i = 0; i < len; ++i) {
        //do char to int conversion on every element of char array
        hex[i] = string[i] - '0';
    }

    //return integer array
    return hex;
}

关于将 unsigned char(数组)转换为 unsigned int(数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40929278/

相关文章:

c - 尝试从 C 连接到 postgres 时出现问题

c - 如何在 Linux 中从另一个进程触发一个进程?

PHP 正则表达式仅提取不同字符串的部分

c - 在处理 C 结构数组时,(*(data+i)).member 是否与 data[i].member 相同?

javascript - 对对象数组进行排序并取 N 个元素

c++ - 在位数组中找到 N 个 1 位的字符串

c++ - 为具有 1 和 2 字节字符的字符集实现退格

c++ - 将二维数组和字符串 vector 作为参数传递给函数

c - 如何用C语言生成日志文件?

java - 如何用R语言打印java.util.Date类型数组的所有元素的值