简体   繁体   English

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

[英]C++ convert from int to byte array, then convert that byte array back to int, cause overflow

I'm making a multiplayer game where I use CSocket to send data between server and clients, and I need to transfer raw bytes.我正在制作一个多人游戏,我使用 CSocket 在服务器和客户端之间发送数据,我需要传输原始字节。 So I tested out how to convert from integer to byte array and reverse, this is what I tested:所以我测试了如何从 integer 转换为字节数组并反转,这就是我测试的:

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

int test2;
copy(bytes, bytes + 3, &test2);
cout << "Test " << test2 << endl;

The test2 variable when printed out, the value isn't 257 but 1 instead, I think it's because type byte (unsigned char) has size of 256 and it is experiencing an overflow.打印出来的 test2 变量,值不是 257 而是 1,我认为这是因为类型 byte(无符号字符)的大小为 256 并且它正在经历溢出。 Is there anyway I can convert properly?无论如何我可以正确转换吗?

All pointer arithmetic will be done in units of the base type.所有指针运算都将以基本类型为单位完成。

For a pointer to int ( int* ) then adding 3 will add a byte-offset of 3 * sizeof(int) .对于指向int ( int* ) 的指针,添加3将添加3 * sizeof(int)的字节偏移量。

So the call copy(&test1, &test1 + 3, bytes) will copy 3 int values into the four-byte array.所以调用copy(&test1, &test1 + 3, bytes)会将3 int值复制到四字节数组中。

To copy only one int then add 1 instead:要仅复制一个int ,然后添加1

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

It might help to see any pointer as a pointer to the first element of an array.将任何指针视为指向数组第一个元素的指针可能会有所帮助。

For &test1 it's could then be seen as a pointer to the first element of an array of a single int element.对于&test1 ,它可以被视为指向单个int元素的数组的第一个元素的指针。


And as mentioned in a comment (thanks for pointing it out john) you only copy three bytes from the bytes array into test2 .正如评论中提到的(感谢约翰指出),您只需将bytes数组中的三个字节复制到test2中。

The end "iterator" should be one element beyond the end, which is a pointer to bytes[4] .结尾的“迭代器”应该是结尾之后的一个元素,它是指向bytes[4]的指针。 That is you need那就是你需要

copy(bytes, bytes + 4, &test2);

Here's your code fixed这是您修复的代码

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;

I convert all the pointers to char pointers, and I use +4 not +3.我将所有指针转换为 char 指针,我使用 +4 而不是 +3。 +3 only copies three bytes so it fails to copy the last byte. +3 仅复制三个字节,因此无法复制最后一个字节。

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

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