Thursday, 22 August 2013

Convert C char to UTF-16 for transmission over network

Convert C char to UTF-16 for transmission over network

I'm writing a program that will interface with another machine running
Java, and I need to send character arrays over the network. On the
receiving end, the Java program uses DataInputStream's readChar() function
and expects characters. However, since characters are stored as 1 byte in
C, I'm having some trouble writing to the network.
How would I go about converting this?
The actual protocol specification is like so:
short: Contains length of char array
char 1, 2, 3...: The characters in the array
For background information, my short conversion is like so:
char *GetBytesShort(short data)
{
short net_data = NET_htons(data);
char *ptr = (char *) malloc(sizeof(short));
memcpy(ptr, &net_data, sizeof(short));
return ptr;
}
I've tested it on the receiving end in Java, and the short does get sent
over correctly with the correct length, but the character array does not.
Thanks in advance!

No comments:

Post a Comment