简体   繁体   中英

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. So I tested out how to convert from integer to byte array and reverse, this is what I tested:

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. 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) .

So the call copy(&test1, &test1 + 3, bytes) will copy 3 int values into the four-byte array.

To copy only one int then add 1 instead:

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.


And as mentioned in a comment (thanks for pointing it out john) you only copy three bytes from the bytes array into test2 .

The end "iterator" should be one element beyond the end, which is a pointer to 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. +3 only copies three bytes so it fails to copy the last byte.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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