Short to char array and back.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jackmejia
    New Member
    • Aug 2007
    • 5

    Short to char array and back.

    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
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Char (byte) arrays may be aligned on odd number boundaries so just casting
    the address of that array to an (unsigned?) short may be tricky. Better construct
    your short from the two char elements in the array; you have to decide on big or
    little endianness though.

    Vice versa doesn't work either because of that alignment; better decompose the
    (unsigned?) short into the individual byte (char) values for your array.

    Or use memcpy() back and forth:

    [code=c]
    short s= 0x1234;
    char a[sizeof(short)];

    memcpy(&s, a, sizeof(short)); // copy a to s
    memcpy(a, &s, sizeof(short)); // and back to s again
    [/code]

    kind regards,

    Jos

    Comment

    Working...