putting a numeric value into an array of chars?

This is a discussion on putting a numeric value into an array of chars? within the C++ Programming forums, part of the General Programming Boards category; hi, i'm sending a socket message with the format Code: char comm // command. 1 byte ushort size // size ...

  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,670
    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);



    ITSA
    Socket Library!

  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, 01: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, 12: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, 06:34 PM
  5. Array of pointers (chars)
    By Vber in forum C Programming
    Replies: 5
    Last Post: 02-08-2003, 03:29 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21