how to convert byte array into integer

M

msosno01

I have Java client that connects to C++ server. The client sends
integer in binary using DataOutputStream write function. I am reading
these data into buffer. I have to convert this buffer back into
integer, but I am not sure how to do it.
This is my code:
int32_t var1;
uint8_t buf[4];

soc = accept();
while (true)
{
socket->recv(&buf, 4);
var1 = htonl(buf);//here I have to do casting. My supervisor
said that I must
//use "void *".
//I tried different combinations
like: (char*)(void *)buf, but everything failed
//in the best case, I've been
getting some huge numbers (all I was sending
//was numerical one)
}
Any help is appreciated.
 
T

Thomas J. Gritzan

I have Java client that connects to C++ server. The client sends
integer in binary using DataOutputStream write function. I am reading
these data into buffer. I have to convert this buffer back into
integer, but I am not sure how to do it.
This is my code:
int32_t var1;
uint8_t buf[4];

soc = accept();
while (true)
{
socket->recv(&buf, 4);
var1 = htonl(buf);//here I have to do casting. My supervisor

Must be ntohl (since you are converting from _n_etwork to _h_ost byte order.
Try this:

socket->recv((void*)&var1, 4);
var1 = ntohl(var1);

Actually, you don't need the cast (conversion to void* is done
automatically), and an C++ style cast (reinterpret_cast) would be preferred.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top