• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Converting a long to byte[] and back again

 
David McCombs
Ranch Hand
Posts: 212
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Henry Wong
author
Marshal
Pie
Posts: 21021
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
David McCombs
Ranch Hand
Posts: 212
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic