简体   繁体   English

memcpy-字节的int变量

[英]memcpy - int variable to BYTE

I am trying to create a data packet, using memcpy . 我正在尝试使用memcpy创建一个数据包。 I expect to see the output in pOutBuffer , whose first four bytes will have 999, followed by 111 followed by 12; 我希望看到pOutBuffer的输出,其前四个字节为999,然后为111,然后为12; But currently i am getting some garbage. 但是目前,我得到一些垃圾。

The problem is that instead of copying the value, it copies the address, I think. 问题是,我认为它不是复制值,而是复制地址。 How can i copy these values in to a contiguous memory so that i can write it to disk and can retrieve the data at the receiving end with my defined format? 如何将这些值复制到连续的内存中,以便可以将其写入磁盘并可以使用定义的格式在接收端检索数据?

Thanks. 谢谢。

#include "stdafx.h"
#include "windows.h"
typedef struct
{
    int Begin;
    int End;
    int Size;
}PACKET;


void AddBuffer(PACKET* pPacket, BYTE* pOutBuffer)
{
    memcpy(pOutBuffer, &pPacket->Begin, sizeof(int));
    memcpy(pOutBuffer+sizeof(int), &pPacket->End, sizeof(int));
    memcpy(pOutBuffer+sizeof(int)+sizeof(int), &pPacket->Size, sizeof(int));
}

int _tmain(int argc, _TCHAR* argv[])
{
    PACKET* pPacket = new PACKET;
    pPacket->Begin = 999;
    pPacket->End   = 111;
    pPacket->Size  = 12;

    BYTE* pOutBuffer = new BYTE [pPacket->Size];
    AddBuffer(pPacket, pOutBuffer);

    //Write pOutBuffer on to the disk 
    //WriteFile(vhFileToWrite,(BYTE*)pOutBuffer,pPacket.Size,&vRetFileSize,NULL);

    //Delete pOutBuffer
    return 0;
}

Source sample has been updated. 源样本已更新。 It now builds ok 现在可以了

Your code works correctly. 您的代码正常工作。 On a little-endian machine with sizeof(int)==4, the number 999 will be stored as the four bytes 0xe7, 0x03, 0x00, 0x00. 在sizeof(int)== 4的小端计算机上,数字999将存储为四个字节0​​xe7、0x03、0x00、0x00。

You said you saw the character 'ç': That is because you are trying to view the array as a string, and ç has the character code 0xe7, which is indeed the first byte written. 您说您看到了字符'ç':这是因为您试图将数组视为字符串,并且ç具有字符代码0xe7,这实际上是写入的第一个字节。 If you view it as an array (either using Visual Studio's memory view, or by typing pOutBuffer,12 in the watch window), you will see the correct byte values. 如果将其视为数组(使用Visual Studio的内存视图或在监视窗口中键入pOutBuffer,12 ),则将看到正确的字节值。

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

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