alaudo <[EMAIL PROTECTED]> writes: > I've got a strange problem with changing my unsigned short values from > host to the network byte order and vice versa. > I have a client and a server, which communicate via their own binary > protocol. I need to send some numerical values of unsigned short type, > so in the client I do the following:
Please next time post a minimal program that your audience can copy&paste&compile&run to (attempt to) see what you are seeing. > typedef unsigned short order_id_t; > ... > order_id_t orderNum; // variable declaration > ... > /* I generate a binary message of MSG_LENGTH length and copy the id to > it */ > void *msg; //binary message > msg = (void *) malloc(MSG_LENGTH); 1. variables are best initialized in their definition. 2. why do you cast from void * to void *? > orderNum = htons(orderNum); > memcpy(msg+OFFSET,&orderNum,sizeof(order_id_t)); > > /* Now I face a strange problem */ > fprintf(stdout,"Your ID is:%d",ntohs(orderNum)); // here the correct > number is written to the stdout %d indicates that the following argument is of type int (or a type promoted to int). In fact, it has an unsigned type (uint16_t on my machine). > fprintf(stdout,"Your ID is:%d",ntohs( (order_id_t) *(msg+OFFSET))); // > here t I get strange values, as if I had only the higher byte > // e.g., if orderNum is < 255, then I get 0, 256 gives me 256 correct, > 257...260 all give 256 etc. The expression *(msg+OFFSET) dereferences a pointer to void. And depending on the actual value of OFFSET, msg+OFFSET may not be suitable aligned for type order_id_t. When I compile #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> int main() { size_t const MSG_LENGTH = 100; size_t const OFFSET = 0; typedef unsigned short order_id_t; order_id_t orderNum = 17; void *msg = malloc(MSG_LENGTH); orderNum = htons(orderNum); memcpy(msg+OFFSET,&orderNum,sizeof(order_id_t)); fprintf(stdout,"Your ID is:%u",ntohs(orderNum)); fprintf(stdout,"Your ID is:%u",ntohs( (order_id_t) *(msg+OFFSET))); } as C++ using gcc 4.1.2, I get: test.cpp: In function 'int main()': test.cpp:17: error: pointer of type 'void *' used in arithmetic test.cpp:22: error: pointer of type 'void *' used in arithmetic test.cpp:22: error: 'void*' is not a pointer-to-object type When I compile it as C, I get: test.cpp: In function 'main': test.cpp:22: warning: dereferencing 'void *' pointer test.cpp:22: error: void value not ignored as it ought to be _______________________________________________ help-gplusplus mailing list help-gplusplus@gnu.org http://lists.gnu.org/mailman/listinfo/help-gplusplus