将unsigned char数组转换为十六进制

时间:2016-12-12 06:18:21

标签: c arrays

我想将unsigned char转换为hex(使用unsigned int)。到目前为止这是我的代码。我有一个program1生成一个unsigned char数组,另一个program2只接受hex(使用unsigned int),所以我想要实现的是获取unsigned char数组的输入并将该数组转换为hex。

(例如,program1输出“1234567812345678”,program2应输出“31323334353637383132333435363738”)

对不起,这个问题似乎很愚蠢。在这里寻找答案,但它似乎不是我想要的。

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;

}

4 个答案:

答案 0 :(得分:1)

如果你需要做的只是打印值,那么你不需要进行任何转换。只需在原始数组上使用 Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); Graphics graph = Graphics.FromImage(bmp as Image); graph.CopyFromScreen(0, 0, 0, 0, bmp.Size); ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg); System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L); myEncoderParameters.Param[0] = myEncoderParameter; bmp.Save("TestPhotoQualityFifty.jpg", jpgEncoder, myEncoderParameters); myEncoderParameter = new EncoderParameter(myEncoder, 100L); myEncoderParameters.Param[0] = myEncoderParameter; bmp.Save("TestPhotoQualityHundred.jpg", jpgEncoder, myEncoderParameters); myEncoderParameter = new EncoderParameter(myEncoder, 0L); myEncoderParameters.Param[0] = myEncoderParameter; bmp.Save("TestPhotoQualityZero.jpg", jpgEncoder, myEncoderParameters); printf

%.2x

即使你想在其他函数中使用数组,int main (void) { int i; unsigned char key[16] = "1234567812345678"; for(i = 0; i < 16; i++) printf("%.2x", key[i]); return 0; } 中存储的实际字节也是ascii字符,即key 0x31等。你通常可以直接使用数组0x32

编辑:要将输出存储在字符数组中,可以使用key功能。

sprintf

另请注意,原始数组char hex[33]; for(i = 0; i < 16; i++) sprintf(hex+2*i, "%.2x", key[i]); 应为17个字节,以便最后考虑key

答案 1 :(得分:1)

以下是我的看法 - phex()函数转换任何数据 在内存中包含一个包含十六进制表示的新分配字符串。

main()函数显示了一个示例用法。示例31323334353637383930的输出为“data”。

#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;
}

答案 2 :(得分:0)

我将函数签名视为

$(document).ready(function(){
$('.regForm').submit(function(event) {

    var formData = {
        'fname' : $('input[fname=fname]').val(),
        'midname' : $('input[midname=midname]').val(),
        'lname' : $('input[lname=lname]').val(),
        'uname' : $('input[uname=uname]').val(),
        'pass' : $('input[pass=pass]').val()
    };

    $.ajax({
        type: 'POST',
        url: 'registeruser.php',
        data: formData,
        datatype: 'json',
        encode: true
    })

    .done(function(data) {
        alert('registerd successfully');
    });

    event.preventDefault();
    });


});

所以我想,你不需要 uint64_t phex (unsigned char[16], long); 数组来转换一个字符串,代表一个数字(也许我错了,你想将每个字符从其char表示转换为int并显示为十六进制数)。

首先,让我们考虑以下代码进行十进制转换(实际上,示例中的数字 - uint64_t - 看起来像十进制数字):

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;

}

注意:您的示例代码中存在错误 - #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; } 从函数返回uint64_t* keyHex(不是指针``uint64_t *`),但如果你接受我的想法,你根本不需要指针。

答案 3 :(得分:0)

如果任务是将字符('1','2'等)转换为十六进制表示(31表示'1',32表示'2'等),很难理解为什么需要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;
}