I have a char xyz[2];
I receive 2 octet numbers in network byte order in xyz[0] and xyz[1].How do i change this to host order.
How do i use ntohs to convert xyz. Please help.
I have a char xyz[2]; I receive 2 octet numbers in network byte order
Share
Do you mean “How do I convert a data stream in network order to a data stream in host order?” In that case you can use the
ntohs()/htons()functions. Be careful how you invoke those, though, since you may have to take alignment issues into account. The universal solution would be to do a manual swapping of the (or each) pair of bytes.On the other hand, if you want to deserialize data that comes to you in network order, and you want to use the values that are serialized in the data in your program, then the notion of a “host order” is a red herring. All you need to know whether the data that you receive is in big-endian or little-endian order:
This is a typical hallmark of platform-independent programming: Your program interna should be entirely independent of implementation details, and fixed implementations have to be specified precisely at the program boundaries (i.e. (de)serialization).
Note that in general, you cannot just take an existing byte buffer and interpret it as a different value in place, since that is not allowed by the standard. That is, you can only treat data as an
intthat has been declared as an int. For example, the following is illegal:char * buf = get(); int a = *(int*)buf;. The legal version starts with the target type:int a; get_data((char*)&a);