I'm currently trying to convert an integer into a char* in order to send it over a socket. In the receiving method I logically try to treat the char* as an integer again, but I seem to be missing something because I can't get it right.
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int num1 = 42; // Works
int num2 = 100; // Works
int num3 = 126; // Works
int num4 = 517; // Doesn't seem to work for int > 127
char p1[sizeof(int)];
*p1 = num1;
char p2[sizeof(int)];
*p2 = num2;
char p3[sizeof(int)];
*p3 = num3;
char p4[sizeof(int)];
*p4 = num4;
void* pA = p4;
void* pB = &num4;
int result1 = static_cast<int>(*p1);
int result2 = static_cast<int>(*p2);
int result3 = static_cast<int>(*p3);
int result4 = static_cast<int>(*p4);
int resultV1 = *static_cast<int*>(pA);
int resultV2 = *reinterpret_cast<int*>(p3);
unsigned int resultV3 = static_cast<int>(*p4);
int resultV4 = *static_cast<int*>(pB); // Works, but I need to convert a char* into an int, not a void* into an int
cout << "R1: " << result1 << endl;
cout << "Expected: " << num1 << endl << endl;
cout << "R2: " << result2 << endl;
cout << "Expected: " << num2 << endl << endl;
cout << "R3: " << result3 << endl;
cout << "Expected: " << num3 << endl << endl;
cout << "R4: " << result4 << endl;
cout << "Expected: " << num4 << endl << endl;
cout << "RV1: " << resultV1 << endl;
cout << "Expected: " << num4 << endl << endl;
cout << "RV2: " << resultV2 << endl;
cout << "Expected: " << num4 << endl << endl;
cout << "RV3: " << resultV3 << endl;
cout << "Expected: " << num4 << endl << endl;
cout << "RV4: " << resultV4 << endl;
cout << "Expected: " << num4 << endl << endl;
getchar();
return 0;
}
I have absolutely no idea how to solve this problem at this point. I tried several other ways, but none of them seemed to work correctly yet. It is essential that the integer is converted into a char* first as the recv() method in the WinSock-API stores its read bytes in a buffer char-array.
Any explanations or solutions? Thanks in advance.