Thread: putting a numeric value into an array of chars?

  1. #1
    Registered User
    Join Date
    Nov 2002
    Posts
    2

    putting a numeric value into an array of chars?

    hi, i'm sending a socket message with the format

    Code:
    char comm // command. 1 byte
    ushort size // size of following data. 2 bytes
    char data[size] // miscellaneous data. size bytes
    
    // i try to put it into a buffer like this.
    
    char *buf = new char[size+3];
    buf[0] = comm;
    buf[1] = (char)size;
    buf[2] = (char)size+1;
    strcpy(buf+3, data);
    send(s, buf, size+3, 0);
    but this doesnt seem to work with the size, as at the other end it always comes out as a different value.

    anyone know how to do this?

  2. #2
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    The high order bytes of the number cannot be cast from a char. Try this:

    Code:
    int sz = sizeof(ushort);
    char *buf = new char[ size + sz ];
    buf[0] = comm;
    memcpy(&buf[1], &size, sz);
    strcpy(buf+sz+1, data);
    send(s, buf, size+sz+1, 0);
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  3. #3
    Registered User
    Join Date
    Nov 2002
    Posts
    2

    Smile

    thank you very much!
    that does the trick

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Rand function for array of chars
    By JFonseka in forum C Programming
    Replies: 7
    Last Post: 02-24-2008, 02:55 PM
  2. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  3. Type and nontype parameters w/overloading
    By Mr_LJ in forum C++ Programming
    Replies: 3
    Last Post: 01-02-2004, 01:01 AM
  4. Putting strings into an array from a text file.
    By JLan in forum C Programming
    Replies: 5
    Last Post: 11-20-2003, 07:34 PM
  5. Array of pointers (chars)
    By Vber in forum C Programming
    Replies: 5
    Last Post: 02-08-2003, 04:29 AM