-2

I thought that the casting between int and byte[] is so easy and I have tried to cast a value to byte[] and then recast the value in other function to get int. Such as, int x = 89; and byte [] y;, the casting y=(byte[])x, not worked. How can I do that ? What I have want, for example :

                       in func1                          in func2
int x ;         x value is casted in the y        y is taken and x value is 
byte[] y;                                             extracted

       ------func1-----------  --------func2---------
       ^                    ^ ^                     ^
x = 33 ==feed into==> byte [] ===> extraction ===> 33 
user2349809
  • 11
  • 1
  • 5

2 Answers2

1

Use ByteBuffer class

ByteBuffer b = ByteBuffer.allocate(4);
b.putInt(0xABABABAB);
byte[] arr = b.array();

BigInteger class.

byte[] arr = BigInteger.valueOf(0xABABABAB).toByteArray();
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
0

You can't use types casts to do this kind of thing in Java. These are conversion, and have to be done programatically.

For example:

    int input = ...
    byte[] output = new byte[4];
    output[0] = (byte) ((input >> 24) & 0xff);
    output[1] = (byte) ((input >> 16) & 0xff);
    output[2] = (byte) ((input >> 8) & 0xff);
    output[3] = (byte) (input & 0xff);

(There are more elegant ways of doing this particular conversion.)

Going from a byte[] to "something else" is similarly a conversion ... which may or may not be possible, depending on what the "something else" is.

For conversion back to an int:

    byte[] input = ... 
    int output = (input[0] << 24) | (input[1] << 16) | (input[2] << 8) | input[3]

This Q&A gives other ways to do this for int <-> byte[]: Java integer to byte array

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216