Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;将int转换为字节数组,然后将该字节数组转换回int,导致溢出_C++_Arrays_Integer_Byte_Overflow - Fatal编程技术网

C++ C++;将int转换为字节数组,然后将该字节数组转换回int,导致溢出

C++ C++;将int转换为字节数组,然后将该字节数组转换回int,导致溢出,c++,arrays,integer,byte,overflow,C++,Arrays,Integer,Byte,Overflow,我正在制作一个多人游戏,我使用CSocket在服务器和客户端之间发送数据,我需要传输原始字节。所以我测试了如何从整数到字节数组的转换和反转,这就是我测试的: int test1 = 257; byte bytes[4]; copy(&test1, &test1 + 3, bytes); int test2; copy(bytes, bytes + 3, &test2); cout << "Test " << test2 <

我正在制作一个多人游戏,我使用CSocket在服务器和客户端之间发送数据,我需要传输原始字节。所以我测试了如何从整数到字节数组的转换和反转,这就是我测试的:

int test1 = 257;
byte bytes[4];
copy(&test1, &test1 + 3, bytes);

int test2;
copy(bytes, bytes + 3, &test2);
cout << "Test " << test2 << endl;
inttest1=257;
字节[4];
复制(&test1,&test1+3,字节);
int test2;
复制(字节、字节+3和测试2);

cout所有指针运算都将以基本类型为单位进行

对于指向
int
int*
)的指针,添加
3
将添加
3*sizeof(int)
的字节偏移量

因此调用
copy(&test1,&test1+3,bytes)
3
int
值复制到四字节数组中

要仅复制一个
int
,请改为添加
1

copy(&test1, &test1 + 1, bytes);

将任何指针视为指向数组第一个元素的指针可能会有所帮助

对于
&test1
而言,它可以被视为指向单个
int
元素数组的第一个元素的指针


正如在评论中提到的(感谢john指出),您只需将
bytes
数组中的三个字节复制到
test2

end“iterator”应该是end后面的一个元素,它是指向
字节[4]
的指针。这就是你需要的

copy(bytes, bytes + 4, &test2);
这是你的密码

int test1 = 257;
byte bytes[4];
copy((char*)&test1, (char*)&test1 + 4, bytes);

int test2;
copy(bytes, bytes + 4, (char*)&test2);
cout << "Test " << test2 << endl;
inttest1=257;
字节[4];
复制((char*)和test1,(char*)和test1+4,字节);
int test2;
复制(字节,字节+4,(字符*)和测试2);

将字节复制回intI时是否会出现另一个
+3
错误?我还想知道代码是否存在可能的结尾问题。复制到字节数组是作为单个int完成的,但复制回数组是作为字节完成的。@john如果在同一个系统上来回复制,则不应该有任何endianness问题。