1

How can I split a variable into single bytes in java? I have for example following snippet in C++:

    unsigned long someVar;
    byte *p = (byte*)(void*) someVar; // byte being typedef unsigned char (from 0 to 255)

    byte *bytes = new byte[sizeof(someVar)];

    for(byte i = 0;i<sizeof(someVar);i++)
    {
        bytes[i] = *p++;
    }

    .... //do something with bytes

I want to accomplish the same under java, but I can't seem to find an obvious workaround.

Michael-O
  • 18,123
  • 6
  • 55
  • 121
Alan Cor
  • 226
  • 1
  • 4
  • 10
  • @ChristofferHammarström, absolutely true. Changed question. – Michael-O Apr 01 '13 at 20:59
  • Are you looking something like this? http://stackoverflow.com/questions/1936857/convert-integer-into-byte-array-java – Dinakar Apr 01 '13 at 21:00
  • @Dinakar yes, sorry I didn't find it. – Alan Cor Apr 01 '13 at 21:07
  • BTW, the question you ask is not quite well-defined: The result of your code will depend on the endianness of the platform it's running on (and on the platform's integer representation, and on the relative sizes of `char` and `long` - just to nitpick). Do you want the same in Java? – sleske Apr 02 '13 at 05:38
  • @sleske That's true, though I rarely program for other platforms different than windows. If possible I would like to have the same behaviour in java. – Alan Cor Apr 02 '13 at 12:04

2 Answers2

3

There are two ways to do it with the ByteBuffer class. One is to create a new byte array dynamically.

long   value = 123;
byte[] bytes = ByteBuffer.allocate(8).putLong(value).array();

Another is to write to an existing array.

long   value = 123;
byte[] bytes = new byte[8];

ByteBuffer.wrap(bytes).putLong(value);

// bytes now contains the byte representation of 123.
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • The question was a bit different: if you have some variable - how to access it in byte-by-byte manner – pmod Apr 01 '13 at 20:58
  • You can wrap a variable in a ByteBuffer and invoke get() which will return the value byte by byte. – Tansir1 Apr 01 '13 at 21:07
  • Thank you, that was what I needed, as also pointed in the link provided in one of the comments. – Alan Cor Apr 01 '13 at 21:08
0

If you use Guava, there is a convenience Longs.toByteArray. It is simply a wrapper for John's ByteBuffer answer above, but if you already use Guava, it's slightly "nicer" to read.

Steven Schlansker
  • 37,580
  • 14
  • 81
  • 100