java - Convert long to "unsigned, 4 byte integer in network byte order" with ByteBuffer -
the protocol i'm using requires sending current position in file "unsigned, 4 byte integer in network byte order". there several questions on this, assuming i'm using integers, not longs
i attempting port nio's bytebuffer can sent in socket channel:
long bytestransfered = ... number of bytes transfered... //todo: do? outbuffer[0] = (byte) ((bytestransfered >> 24) & 0xff); outbuffer[1] = (byte) ((bytestransfered >> 16) & 0xff); outbuffer[2] = (byte) ((bytestransfered >> 8) & 0xff); //todo: why netbeans nothing? outbuffer[3] = (byte) ((bytestransfered >> 0) & 0xff);
are methods in bytebuffer accomplish this? in more obvious, self-descriptive way bit-shifting magic above?
whether signed or unsigned, bits same.
if cast long
int
, jvm discards high-order bits. issue comes when promoting int
long
: java sign-extend value, filling in high-order bits of long
most-significant bit of int
.
to resolve problem, apply mask long. following should make clear:
long value = integer.max_value + 1234l; system.out.println("original value = " + value); int ivalue = (int)value; system.out.println("value int = " + ivalue); byte[] array = new byte[4]; bytebuffer buf = bytebuffer.wrap(array); buf.putint(0, ivalue); int iretrieved = buf.getint(0); system.out.println("int buf = " + iretrieved); long retrieved = iretrieved; system.out.println("converted long = " + retrieved); retrieved = retrieved & 0xffffffffl; system.out.println("high bytes masked = " + retrieved);
however, aware still have 32 bits. if filesizes greater 4gb won't able fit 4 bytes (and if have worry files > 2g, should worry files > 4g).
Comments
Post a Comment