aspose file tools*
The moose likes Java in General and the fly likes Java equivilent for the c++ functions htonl and ntohl Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Java equivilent for the c++ functions htonl and ntohl" Watch "Java equivilent for the c++ functions htonl and ntohl" New topic
Author

Java equivilent for the c++ functions htonl and ntohl

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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

Joined: Jan 14, 1999
Posts: 165
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 )


With best of best regards, Pawel S. Veselov ( aka Black Angel )
Ladoo Gopal
Greenhorn

Joined: Nov 24, 2003
Posts: 1
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;
}
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Java equivilent for the c++ functions htonl and ntohl