Re: Long integer to bytes?
nooneinparticular314159@yahoo.com wrote:
I'm attempting to implement a well defined protocol which has been
widely implemented. I can't alter the protocol if I want to
interoperate with existing implementations.
What I have gotten working is the use of BigIntegers internally within
my program, but then I convert the last four bytes to a ByteArray,
which means that I can send them over the network to other hosts
running other implementations.
Just use a DataOutputStream.
The unsigned arithmetic can be performed using longs. When you are ready to
output the data you mask the low order 4 bytes into an int. Then write the int
directly to the network using DataOutputStream.writeInt(). Java I/O is all
network byte order (big endian) so there's no need to worry about byte
swapping.
The following code will write the unsigned value 0xfedcba01 to a file:
package tests;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
public class IntOutput {
public static void main(String[] args) {
// create a 32bit, "unsigned" integer.
long l = 0xfedcba01L;
// mask off the 32bit low order bits into an int.
int i = (int) l & 0xffffffff;
System.out.println(l);
System.out.println(i);
try {
// open a DataOutputStream, in this case to a file, but it could
// just as easily be network connection.
FileOutputStream fos = new FileOutputStream("tmp.tmp");
DataOutputStream dos = new DataOutputStream(fos);
dos.writeInt(i);
dos.close();
fos.close();
}
catch(Exception e) {
System.err.println(e);
}
}
}
When you run it the output is:
4275878401
-19088895
The contents of the output file, when viewed using od are:
$ od -t x4 tmp.tmp
0000000 fedcba01 HEX
$ od -D tmp.tmp
0000000 4275878401 Unsigned int
$ od -t d4 tmp.tmp
0000000 -0019088895 Signed int
--
Nigel Wade, System Administrator, Space Plasma Physics Group,
University of Leicester, Leicester, LE1 7RH, UK
E-mail : nmw@ion.le.ac.uk
Phone : +44 (0)116 2523548, Fax : +44 (0)116 2523555