[ee122] More byte ordering..

Daniel Killebrew dank at eecs.berkeley.edu
Mon Nov 26 15:54:57 PST 2007



Anthony Kilman wrote:
> Quick question. Suppose we want to convert everything (Jorge I think a
> previous email you sent suggested to convert "everything" to network
> byte order to be safe...) in a packet to network byte ordering... and we
> treat the data as a character array. Also suppose as an example my
> machine is "blah" endian, and network ordering is the opposite. I
> already know for an integer:
>
> // "blah" endian
> foobar = 3937
> 00000000 00000000 00001111 01100001
>
> // network "endian"
> nFoobar = 1628372992
> 01100001 00001111 00000000 00000000
>
> But does the same apply to a character array?
>   
You don't need to (nor can you) convert arrays of bytes (and char is 1 
byte) to network byte order. As the name indicates, it is network *byte 
*ordering, not bit ordering. The bit ordering takes care of itself. So 
if you had a string and wanted to send it over the network, you would 
just call send(string);

This only works for data that is truly an array of bytes. If you were 
asking if the following would work, it would not:
int foo = 3937;
send(sock, (char*)&foo, 4, 0);
--- the receiver's end--
int bar;
recv(sock, (char*)&bar, 4, 0);
sprintf("bar is wrong: %d", bar);

What I'm saying is: if you are treating data as a character array when 
it's really an integer, or short, or anything that's longer than 1 byte, 
you will run into problems if you don't use htonl, htons, etc..

Daniel
> _______________________________________________
> ee122 mailing list
> ee122 at mailman.ICSI.Berkeley.EDU
> http://mailman.ICSI.Berkeley.EDU/mailman/listinfo/ee122
>
>   


More information about the ee122 mailing list