简体   繁体   English

将无符号字符数组转换为十六进制

[英]Converting unsigned char array to hex

I want to convert unsigned char to hex (using unsigned int). 我想将unsigned char转换为十六进制(使用unsigned int)。 This is my code so far. 到目前为止,这是我的代码。 I have a program1 that produces an unsigned char array and the other program2 only takes in only hex (using unsigned int), so what i want to achieve is getting an input of unsigned char array and converting that array into hex. 我有一个program1,它产生一个无符号char数组,而另一个program2只接受十六进制(使用unsigned int),所以我要实现的是获取无符号char数组的输入并将该数组转换为16进制。

(Eg, program1 outputs "1234567812345678", program2 should output "31323334353637383132333435363738") (例如,program1输出“ 1234567812345678”,program2应输出“ 31323334353637383383132333435363738”)

Sorry if this question seems dumb. 抱歉,这个问题似乎很愚蠢。 Looked around for answers here but it didn't seem to be what I wanted. 在这里四处寻找答案,但这似乎不是我想要的。

uint64_t phex (unsigned char[16], long);



int main (void) {

int i;
unsigned char key[16] = "1234567812345678";


uint64_t* keyHex = phex(key,16); //store into an array here

for(i = 0; i < 16; i++)
printf("%.2x ", keyHex[i]);

free(keyHex);

return 0;

}


uint64_t phex(unsigned char* string, long len)
{

int i;
//allocate memory for your array
uint64_t* hex = (uint64_t*)malloc(sizeof(uint64_t) * 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;

}

If all you need to do is print the values, then you do not need to do any conversion. 如果您只需要打印值,那么您就不需要进行任何转换。 Just use printf %.2x on the original array. 只需在原始阵列上使用printf %.2x

int main (void) {
    int i;
    unsigned char key[16] = "1234567812345678";
    for(i = 0; i < 16; i++)
        printf("%.2x", key[i]);
    return 0;
}

Even if you want to use the array in some other function, the actual bytes stored in key are the ascii characters, ie 0x31 0x32 etc. You can generally directly use the array key 即使您想在其他功能中使用数组, key中存储的实际字节也是ascii字符,即0x31 0x32等。通常,您可以直接使用数组key

Edit: To store the output in a character array, you can use the sprintf function. 编辑:要将输出存储在字符数组中,可以使用sprintf函数。

char hex[33];
for(i = 0; i < 16; i++)
    sprintf(hex+2*i, "%.2x", key[i]);

Also note that the original array key should be 17 bytes to account for the \\0 at the end. 另请注意,原始数组key应为17个字节,以末尾占\\0

Here is my take on it - the phex() function converts any data in memory into a newly allocated string containing the hex representation. 这是我的phex()函数将内存中的任何数据转换为包含十六进制表示形式的新分配的字符串。

The main() function shows an example usage. main()函数显示了用法示例。 The output is " 31323334353637383930 " for the example data . 示例data的输出为“ 31323334353637383930 ”。

#include <stdlib.h> /* malloc() */
#include <stdio.h>  /* sprintf() */
#include <string.h> /* strlen(), in the example main() */

/*
 * Return a hex string representing the data pointed to by `p`,
 * converting `n` bytes.
 *
 * The string should be deallocated using `free()` by the caller.
 */
char *phex(const void *p, size_t n)
{
    const unsigned char *cp = p;              /* Access as bytes. */
    char *s = malloc(2*n + 1);       /* 2*n hex digits, plus NUL. */
    size_t k;

    /*
     * Just in case - if allocation failed.
     */
    if (s == NULL)
        return s;

    for (k = 0; k < n; ++k) {
        /*
         * Convert one byte of data into two hex-digit characters.
         */
        sprintf(s + 2*k, "%02X", cp[k]);
    }

    /*
     * Terminate the string with a NUL character.
     */
    s[2*n] = '\0';

    return s;
}

/*
 * Sample use of `phex()`.
 */
int main(void)
{
    const char *data = "1234567890";               /* Sample data */
    char *h = phex(data, strlen(data));  /* Convert to hex string */

    if (h != NULL)
        puts(h);                                  /* Print result */

    free(h);                             /* Deallocate hex string */
    return 0;
}

I see the function signature as 我看到功能签名为

 uint64_t phex (unsigned char[16], long);

so I think, you do not need array of uint64_t to transform one string, representing one number (perhaps I am wrong and you want to transform each single character from its char-representation to int and show as hexadecimal number). 所以我认为,您不需要uint64_t数组来转换一个字符串,表示一个数字(也许我错了,您希望将每个字符从其char表示形式转换为int并显示为十六进制数字)。

First, let's consider the following code to transformation in decimal (actually, number in your example - 1234567812345678 - looks like decimal number): 首先,让我们考虑以下代码以十进制转换(实际上,示例中的数字1234567812345678看起来像十进制数字):

uint64_t phex(unsigned char* string, long len)
{

    int i;
    //you do not need to allocate memory for array
    uint64_t hex = 0; // just one variable

    for (i = 0; i < len; ++i) {
        hex *= 10; // shift
        hex += string[i] - '0'; // add to the smallest rank
    }

    //return integer Value
    return hex;

}

Then for hexadecimal the program will be: 然后对于十六进制,程序将是:

#include <stdio.h>
#include <stdint.h>
#include <string.h>
uint64_t phex(unsigned char[16], long);

int main(void) {

    int i;
    unsigned char key[16] = "A123B00CF1";


    uint64_t keyHex = phex(key, strlen(key));

    printf("%lld(dec) = %llx(hex)", keyHex, keyHex);

    return 0;
}


uint64_t phex(unsigned char* string, long len)
{
    int i;
    uint64_t hex = 0;
    for (i = 0; i < len; ++i) {
        hex *= 0x10; // shift for one hexadecimal digit
        // -'0' for digits 0..9 and -('A'-10) for digits `A`..`F`
        hex += toupper(string[i]) - ((string[i] >= 'A') ? ('A' - 10) : '0');
        // TODO: Consider making check for characters that are not hexadecimal
        // e.g. use isxdigit(string[i]) in some if statement
    }
    return hex;
}

Note: There is a mistake in your example code - uint64_t* keyHex take the value from function that returns uint64_t (not pointer ``uint64_t*`), but if you accept my idea, you do not need pointer at all. 注意:您的示例代码中有一个错误uint64_t* keyHex从返回uint64_t函数中获取值(不是指针``uint64_t *`''),但是如果您接受我的想法,则根本不需要指针。

If the task is to transform chars ('1', '2', etc.) to their hexadecimal representation (31 for '1', 32 for '2', etc.) it is hard to understand why you need uint64_t . 如果任务是将字符('1','2'等)转换为十六进制表示形式(对于'1'为31,对于'2'为32,等等),很难理解为什么需要uint64_t

But for your task code can be as follows (without uint64_t ): 但是对于您的任务代码,可以如下所示(不带uint64_t ):

#include <stdio.h>
#include <string.h>

unsigned int * phex(unsigned char[16], long);

int main(void) {
    int i;
    unsigned char key[16] = "1234567812345678";
    unsigned* keyHex = phex(key, strlen(key)); // strlen(key) to determine number of characters 
    for (i = 0; i < 16; i++)
        printf("%.2x", keyHex[i]); // you do need space as I see from your example
    free(keyHex);
    return 0;

}


unsigned int * phex(unsigned char* string, long len)
{
    int i;
    //allocate memory for array
    unsigned int * hex = (unsigned int *)malloc(sizeof(unsigned int) * len);
    for (i = 0; i < len; ++i) {
        //no special conversion needed
        hex[i] = string[i];
    }
    //return array with hexadecimal representation for each character in string
    return hex;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM