This week's book giveaway is in the Cloud/Virtualizaton forum.
We're giving away four copies of Mesos in Action and have Roger Ignazio on-line!
See this thread for details.
Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Need Help Converting a long to a Byte Array

 
Randall Stevens
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
in a 32-bit architecture, wouldn't it be 4 bytes and not 8 as your code suggests?
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic