Hello,
I been working on an application that need to build a data package to send it over the network, I have an unsigned short as the data length, this is two bytes.
On the server side I am working on C# and on the client side I am working on C++.
What I precisely need if to mimic some functionality I have on C# provided by the .net Framework.
System.BitConve rter.GetBytes(v alue)
This function takes many data types (unsigned short for my need) and returns an array of bytes with the corresponding value of the data I gave it as parameter.
number 512 becomes,
byte 0 = 0
byte 1 = 2
and the other function that takes a byte array and returns an unsigned integer in my case is
System.BitConve rter.ToUInt16(b yte array,starting index)
this function takes two bytes from the starting index on the byte array becuase UInt16 is two bytes, and returns an unsigned short.
array = { 0,2}
returns 512.
How is the best way to do this, I have tried this method.
clen = new char[2];
*(unsigned short *)clen = m_length;
or
unsigned short* num_addr = &m_length;
char* num_val = (char*)num_addr ;
this give me tha byte array from the short number and the other direction i have implemented this way
number = *(unsigned short *) array;
it works but someone pointed me that using this aproach could be risky in terms of memory handling, that pointing to memory areas with different types of pointers culd lead to problems.
So, which is the best way to do it?
Thanks
I been working on an application that need to build a data package to send it over the network, I have an unsigned short as the data length, this is two bytes.
On the server side I am working on C# and on the client side I am working on C++.
What I precisely need if to mimic some functionality I have on C# provided by the .net Framework.
System.BitConve rter.GetBytes(v alue)
This function takes many data types (unsigned short for my need) and returns an array of bytes with the corresponding value of the data I gave it as parameter.
number 512 becomes,
byte 0 = 0
byte 1 = 2
and the other function that takes a byte array and returns an unsigned integer in my case is
System.BitConve rter.ToUInt16(b yte array,starting index)
this function takes two bytes from the starting index on the byte array becuase UInt16 is two bytes, and returns an unsigned short.
array = { 0,2}
returns 512.
How is the best way to do this, I have tried this method.
clen = new char[2];
*(unsigned short *)clen = m_length;
or
unsigned short* num_addr = &m_length;
char* num_val = (char*)num_addr ;
this give me tha byte array from the short number and the other direction i have implemented this way
number = *(unsigned short *) array;
it works but someone pointed me that using this aproach could be risky in terms of memory handling, that pointing to memory areas with different types of pointers culd lead to problems.
So, which is the best way to do it?
Thanks
Comment