*
The moose likes Beginning Java and the fly likes Need Help Converting a long to a Byte Array 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 "Need Help Converting a long to a Byte Array" Watch "Need Help Converting a long to a Byte Array" New topic
Author

Need Help Converting a long to a Byte Array

Randall Stevens
Ranch Hand

Joined: Jul 01, 2003
Posts: 65
I have a constant and it is a long data type. I need to convert it to a byte array. I have been looking at the Byte parseByte(), but it appears to return a single byte.
What do I need to do in order to convert from a long to a byte array?
Wayne L Johnson
Ranch Hand

Joined: Sep 03, 2003
Posts: 399
It ain't pretty, but it works. It's a matter of using the shift operators to pull out 8 bits at a time. Note that it fills the array from the bottom (bytes[7]), but prints it out in *normal* order. It also destroys the "bigValue" so that by the end it has a value of zero.

There may be prettier ways of doing it, but it seems to work. In a real application you'd want to encapsulate the logic in a separate method.
[ October 22, 2003: Message edited by: Wayne L Johnson ]
Randall Stevens
Ranch Hand

Joined: Jul 01, 2003
Posts: 65
in a 32-bit architecture, wouldn't it be 4 bytes and not 8 as your code suggests?
Wayne L Johnson
Ranch Hand

Joined: Sep 03, 2003
Posts: 399
In Java, anything of type "long" is 64 bits, guaranteed, regardless of what the underlying architecture or OS is. That's why I hard-coded it to 8 bytes.
If Java tried to rely on the underlying OS to determine what a "long" was --or any primitive--then you might have this problem. That's why, in order to ensure "write once, run anywhere," Sun made sure to define the eight primitives, and every JVM honors those definitions. A "long" is a 64-bit signed two's-complement integer.
Michael Fitzmaurice
Ranch Hand

Joined: Aug 22, 2001
Posts: 168
Hi
You could also chain a java.io.DataOutputStream to a java.io.ByteArrayOutputStream - see the API docs for details. I also once wrote a class to do such conversions without using the various IO streams - you can find it online here.
Hope this helps
Michael


"One good thing about music - when it hits, you feel no pain" <P>Bob Marley
 
Consider Paul's rocket mass heater.
 
subject: Need Help Converting a long to a Byte Array
 
Similar Threads
How to convert binary octet string into byte array for writing into socket
Converting an Array with any datatype to byte array
long to byte array
zipEntry.getComment() returns null
How to read "long" in to byte table