unsigned long ,char array,memcpy 困惑
unsigned long firstLength = 20;
char content[100];
memcpy(content,&firstLength ,sizeof(unsigned long));
unsigned long secondLegth = 30;
memcpy(content + sizeof(unsigned long),&secondLegth,sizeof(unsigned long));
int contentLength = strlen(content); //
unsigned long fisrtValue = 0;
memcpy(&fisrtValue,content,sizeof(unsigned long));
unsigned long sencondValue = 0;
memcpy(&sencondValue + 3,content,sizeof(unsigned long));
为什么contentLength 的长度是1而不是8呢,我已经拷贝了8个字节了,
还有fisrtValue 能够得到正确的数据20,但是sencondValue 却得到的0,
请大家帮我分析一下哈,谢谢了
[解决办法]
为什么contentLength 的长度是1而不是8呢,我已经拷贝了8个字节了,
你的环境整数是小端存储,所以content的第一个字节是14,第二个是00
还有fisrtValue 能够得到正确的数据20,但是sencondValue 却得到的0,
(&sencondValue + 3)实际上是加了sizeof(unsigned long *)个长度,sencondValue 并没改变
[解决办法]
strlen返回的是字符串长度,遇到0就停了,而content中的内容是0x140000001E000000......
最后一行如果是要拷回第二值的活,应该是
memcpy(&sencondValue,content+4,sizeof(unsigned long));
[解决办法]
unsigned long firstLength = 20;
char content[100];
memcpy(content,&firstLength ,sizeof(unsigned long));
unsigned long secondLegth = 30;
memcpy(content + sizeof(unsigned long),&secondLegth,sizeof(unsigned long));
int contentLength = strlen(content); // content(20)的二进制你查看一下,第二个字节是0,strlen就认为结束了。所以长度为1.
unsigned long fisrtValue = 0;
memcpy(&fisrtValue,content,sizeof(unsigned long));
unsigned long sencondValue = 0;
memcpy(&sencondValue + 3,content,sizeof(unsigned long));
//why &secondValue+3? should be memcpy(&sencondValue ,content+sizeof(unsigned long),sizeof(unsigned long));??
为什么contentLength 的长度是1而不是8呢,我已经拷贝了8个字节了,
还有fisrtValue 能够得到正确的数据20,但是sencondValue 却得到的0,
请大家帮我分析一下哈,谢谢了
[解决办法]
unsigned long firstLength = 20;
char content[100];
char*pBuffer = content;
memcpy(pBuffer,&firstLength ,sizeof(unsigned long));
pBuffer += sizeof(unsigned long);
unsigned long secondLegth = 30;
memcpy(pBuffer,secondLegth,sizeof(unsigned long));
pBuffer = content;
unsigned long fisrtValue = 0;
memcpy(&fisrtValue,pBuffer ,sizeof(unsigned long));
pBuffer += sizeof(unsigned long);
unsigned long sencondValue = 0;
memcpy(&sencondValue,pBuffer ,sizeof(unsigned long));
socket是会告诉你接受多少字节
用大的buffer接受一般4096 ru char buffer[4096] = {0};
根绝接受的字节数来确认。
对方收到1字节,你先确认一下你发了多少,send后会给你报告的。