gpt4 book ai didi

c - unsigned long 到 char 数组

转载 作者:IT王子 更新时间:2023-10-29 01:03:09 27 4
gpt4 key购买 nike

这是我的代码示例:

/* Standard Linux headers */


/* --------------------------------------------------------------------------
Calculates the CRYPTO
-------------------------------------------------------------------------- */
unsigned long CalculateCRYPTO(
unsigned long ulCount, /* Number of bytes in the data block */
unsigned char *ucBuffer ) /*Data block*/
{
unsigned long ulCRYPTO = 0;
//fonction that i have not coded ...
return( ulCRYPTO );

}


int main (void)
{

/*Variables and socket programming*/

//this is my datablock must be in hexa AA 35 07 (will chnage size and data but for now it's hardcoded)
unsigned char datablock[3];
memset(datablock, '\0' ,sizeof(datablock));
datablock[0]=0xaa;
datablock[1]=0x35;
datablock[2]=0x07;

unsigned long CRYPTO;
CRYPTO=CalculateCRYPTO(sizeof(datablock),datablock); //calculate crypto depending of datablocks
printf("CRYPTO = 0x%08x \n", CRYPTO); //prints me 0xe8ba8fa3 that is what i want

/*Creating the final command*/
//(will chnage size and data but for now it's fixed)
unsigned char cmd_final_hex[7]; //this needs to be DATABLOCKS+CRYPTO
//in hexa AA 35 07 concatenated to inverted CRYPTO so ... A3 8F BA E8 => must be AA 35 07 A3 8F BA E8
memset(cmd_final_hex, '\0' ,sizeof(cmd_final_hex)); //Make sure cmd final is at 0
memcpy(cmd_final_hex, datablock, sizeof(datablock)); //cmd at datablock + 000
// while loop prints me what i want so cmd_final_hex[]=AA 35 07 00 00 ...

//Now i want to concatenate so my idea is to use memcpy and not strcat :
memcpy(&cmd_final_hex[sizeof(datablock)], &CRYPTO, 4);

//and a print gives me AA 35 07 A3 8F BA E8 which is exactly what i want but why do i have to use "&CRYPTO" and not "CRYPTO" in my memcpy. !!!

return 0;


}

我的问题是,为什么最后一个 memcpy 有效?我希望将 CRYPTO 而不是 &CRYPTO 放在参数中......对我来说,CRYPTO 是我想要的值,所以 0xe8ba8fa3 和 &CRYPTO 地址。对我来说,CRYPTO 不是指针,所以为什么我需要将 memcpy 与 &CRYPTO 一起使用才能使其正常工作?

顺便说一句,我的代码可能是纯粹的灾难,我是初学者。请随时纠正我!

谢谢!

最佳答案

My question is, why does this last memcpy works ? i would expect to put CRYPTO and not &CRYPTO in arguments... For me, CRYPTO is the value i want so 0xe8ba8fa3 and &CRYPTO the address.

你是对的。 CRYPTO 不是指针。然而,memcpy需要一个指针,所以我们必须给它一个。我们通过获取 CRYPTO 的地址来做到这一点,这是通过向其添加 & 来完成的,因此是 &CRYPTO

memcpy 所做的是将内存从一个地址复制到另一个地址(这就是它需要两个指针的原因),而不管这些地址的实际内容。如果你给它 CRYPTO 而不是指向它的指针,它可能会将 CRYPTO 的值解释为地址(行为未定义,无法保证会发生什么除非编译器给出一个)。

关于c - unsigned long 到 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53393111/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com