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?
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), 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 ]
Joined: Jul 01, 2003
in a 32-bit architecture, wouldn't it be 4 bytes and not 8 as your code suggests?
Wayne L Johnson
Joined: Sep 03, 2003
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.