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 Android Security Essentials Live Lessons this week in the Android 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

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

Joined: Sep 28, 2004
Posts: 18545

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.


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
Similar Threads
DatagramSocket, receive multiple packets
DatagramPacket::getLength() does not refresh
Networking performance questions
how to know the number of received bytes
How do you read packets off a stream?