简体   繁体   中英

How do you convert an unsigned int[16] of hexidecimal to an unsigned char array without losing any information?

I have a unsigned int[16] array that when printed out looks like this:

4418703544ED3F688AC208F53343AA59

The code used to print it out is this:

for (i = 0; i < 16; i++)
    printf("%X", CipherBlock[i] / 16), printf("%X",CipherBlock[i] % 16);
printf("\n");

I need to pass this unsigned int array "CipherBlock" into a decrypt() method that only takes unsigned char *. How do correctly memcpy everything from the "CipherBlock" array into an unsigned char array without losing information?

My understanding is an unsigned int is 4 bytes and unsigned char 1 byte. Since "CipherBlock" is 16 unsigned integers, the total size in bytes = 16 * 4 = 64 bytes. Does this mean my unsigned char[] array needs to be 64 in length?

If so, would the following work?

unsigned char arr[64] = { '\0' };
memcpy(arr,CipherBlock,64); 

This does not seem to work. For some reason it only copies the the first byte of "CipherBlock" into "arr". The rest of "arr" is '\\0' thereafter.

您为什么不只将CipherBlock指针转换为unsigned char *并将其传递呢?

decrypt((unsigned char *)CipherBlock);

An int is at least 16 bits, same as a short in that regard.

It looks like every unsigned int has values 0-255 or 00-FF in your case, which is a safe range for an unsigned char . However, the proper way to convert one to the other is a cast:

for (int i=0; i<16; ++i) arr[i] = (unsigned char) CipherBlock[i];

But you have not specified what kind of data decrypt() expects. From the signature, I suspect integral data (strings are usually char* or const char* ) but it's hard to be sure without a context.

Note that you could also do printf("%02X", CipherBlock[i]); for printing.

You need to repack the numbers so you can not use memcpy or cast it directly. Aib has it correct.

unsigned char array[16];
for(int i = 0; i < 16; i++) {
    array[i] = CipherBlock[i];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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