简体   繁体   English

如何在不丢失任何信息的情况下将十六进制的unsigned int [16]转换为unsigned char数组?

[英]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: 我有一个无符号的int [16]数组,在打印时看起来像这样:

4418703544ED3F688AC208F53343AA59 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 *. 我需要将此无符号的int数组“ CipherBlock”传递到仅采用无符号char *的解密()方法中。 How do correctly memcpy everything from the "CipherBlock" array into an unsigned char array without losing information? 如何正确地将所有内容从“ CipherBlock”数组存储到一个未签名的char数组而又不丢失信息?

My understanding is an unsigned int is 4 bytes and unsigned char 1 byte. 我的理解是unsigned int是4个字节,unsigned char是1个字节。 Since "CipherBlock" is 16 unsigned integers, the total size in bytes = 16 * 4 = 64 bytes. 由于“ CipherBlock”是16个无符号整数,因此总大小(以字节为单位)= 16 * 4 = 64字节。 Does this mean my unsigned char[] array needs to be 64 in length? 这是否意味着我的无符号char []数组的长度必须为64?

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". 由于某种原因,它仅将“ CipherBlock”的第一个字节复制到“ arr”。 The rest of "arr" is '\\0' thereafter. 此后,其余的“ arr”为“ \\ 0”。

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

decrypt((unsigned char *)CipherBlock);

An int is at least 16 bits, same as a short in that regard. int 至少为 16位,在这方面与short相同。

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 . 在您的情况下,似乎每个unsigned int值都为0-255或00-FF,这是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. 但是您尚未指定decrypt()期望什么样的数据。 From the signature, I suspect integral data (strings are usually char* or const char* ) but it's hard to be sure without a context. 从签名来看,我怀疑整数数据(字符串通常是char*const char* ),但是很难确定是否没有上下文。

Note that you could also do printf("%02X", CipherBlock[i]); 请注意,您还可以执行printf("%02X", CipherBlock[i]); for printing. 用于打印。

You need to repack the numbers so you can not use memcpy or cast it directly. 您需要重新打包数字,以便不能使用memcpy或直接对其进行转换。 Aib has it correct. Aib说的没错。

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

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

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