• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Java equivilent for the c++ functions htonl and ntohl

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to access a messaging utility on another machine via sockets. The protocol consists of a signature (4 bytes) and a 4 byte "network long" which is the size of the message being sent. The specs say the following:
"... It should be set using the socket conversion function htonl. It should be read using ntohl socket conversion function. ...". I would greatly appreciate any help you may have on this. You can reply to rwing@pcisys.net if you have any answers.
Thanks,
Rob
------------------
 
Pawel Veselov
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
htonl,htons and ntohl,ntohs are functions to convert from host byte order to network byte order. Network byte order is simple, you send a bytes in the same order you'd write them on a paper i.e. from highest byte to lowest. (For SPARC this function is a bargain, since SPARC uses the same order for integers)
The procedure converting host to net is near the following

<pre>
byte[4] htonl(int x) {
byte [] res = new byte[4];
for (int i=0; i<4; i++) {<br /> res[i] = (x >>> 24);
x <<= 8;
}
return res;
}
</pre>
The array this function returns can be send to the network via OutputStream.write();
The back conversion is about this :

<pre>
int ntohl(byte [4] x) {
int res = 0;
for (int i=0; i<4; i++) {
res <<= 8;
res |= (int)x[i];
}
return res;
}
</pre>

------------------
With best of best regards, Pawel S. Veselov ( aka Black Angel )

 
Ladoo Gopal
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This was a lot of help. To help the next person, here is code with all compilation issues taken care of:
//return bytes will always be 4 bytes long.
byte[] htonl(int x)
{
byte[] res = new byte[4];
for (int i = 0; i < 4; i++)
{
res[i] = (new Integer(x >>> 24)).byteValue();
x <<= 8;
}
return res;
}

//You can only ask for a byte array 4 bytes long to be converted. Rest everything will be ignored.
int ntohl(byte[] x)
{
int res = 0;
for (int i = 0; i < 4; i++)
{
res <<= 8;
res |= (int) x[i];
}
return res;
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic