DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   Data loss in Type Conversion. (http://www.daniweb.com/forums/thread11354.html)

Layla_2401 Sep 25th, 2004 6:49 am
Data loss in Type Conversion.
 
Hello Everyone,

I'm working on a couple of programs, client/server. I'm using winsock library to handle data transfer between the two programs. I'm having a problem when it comes to sending int values, they must be converted to (char *) since that's the data type of the buffers used in the socket Send() and Recv() functions. to elaborate, consider the following:

Client side:
-----------
unsigned char rnd[4];
int noncer =0;

// Generating a random number
RAND_pseudo_bytes(rnd,sizeof(rnd));

noncer = (int)rnd;

non1=(char*)noncer;

// These two lines produce the same output which is 1244556
cout <<"\n Noncer :" << noncer << "\n";
cout.flush();
cout <<"\n Noncer char :" << (int)non1 << "\n";
cout.flush();

SendData(Socket, non1);

Server Side:
-----------
int client_nonce;
char String[50];
String_initialization(String);

// Reading the nonce identifier
RecieveMessage(socket, String, number_of_bytes);
client_nonce = (int)String;

// this results in 1244588 !!
cout<<"\n the nonce is:"<<client_nonce <<endl;
cout.flush();

If anyone can tell me what's causing the change of data i'd really appreciate it.

Thank you all in advance.
Layla.

Narue Sep 25th, 2004 11:01 am
Re: Data loss in Type Conversion.
 
Don't play around with casting like that unless you know what you're doing. Type punning can be tricky business, but barring transmission issues with your sockets, this should work:
#include <cstring>
#include <iostream>

using namespace std;

int main()
{
  int i1 = 12345;
  char buffer[sizeof ( int )];

  memcpy ( buffer, (unsigned char *)&i1, sizeof ( int ) ); // Simulate send/recv

  int *pi = (int *)buffer;
  cout<< *pi <<endl;
}

Layla_2401 Sep 25th, 2004 11:59 am
Re: Data loss in Type Conversion.
 
Hi Narue,

Thank you SO much for your help, I now get the same value at both sides :)

dimkovtrajce Mar 22nd, 2006 5:51 am
Re: Data loss in Type Conversion.
 
Hi I am having the same problem, but I couldnt solve it.
I need to send a CString with Unicode (16bit) to the send and recv function. Unfortunately all i get is garbage :)
Any help is welcomed

Narue Mar 22nd, 2006 9:58 am
Re: Data loss in Type Conversion.
 
Don't resurrect a two year old thread to say "me too"! Start a new thread if you have a new question. Geez.


All times are GMT -4. The time now is 11:03 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC