wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Converting a long to byte[] and back again Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Converting a long to byte[] and back again" Watch "Converting a long to byte[] and back again" New topic
Author

Converting a long to byte[] and back again

David McCombs
Ranch Hand

Joined: Oct 17, 2006
Posts: 212
I have an assignment where I have to implement a simple TCP like protocol over an existing UDP implementation. I choose to use Java, but am having trouble manipulating bytes.

I need to time stamp each packet. I am sending everything in the Datagram Packet as a byte[], but can't seem to convert a byte[] back to a long. Is there a simple way to do this? I looked through the wrapper classes and nothing worked. Is there a way to use the long value returned in Byte.longValue() to being able to figure out how long a packet took to transfer?


"Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration."- Stan Kelly-Bootle
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18754
    
  40

Not sure exactly what you mean by "converting a long to byte[] and back again"... but if you mean... Referencing a byte array of size 8 as a long, or a long as a byte array of size 8, with no data manipulation, then you should take a look at the java.nio.ByteBuffer class.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
David McCombs
Ranch Hand

Joined: Oct 17, 2006
Posts: 212
Thanks, I will check out that class.

What I mean is that I need to send a timestamp inside the DatagramPacket. The data section of the packet contains a byte[]. The first few bytes is header data for my implementation. part of the header is a timestamp.

I call System.currentTimeMillis(). Of course that returns a long. I need to convert it to a byte[] to add to the packet byte[]. When the packet arrives at its destination, the bytes that comprise the time stamp, need to be converted back to a long so it can be used for various purposes.

Hopefully that class will help me out. Thanks again.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Converting a long to byte[] and back again