0

I have a method that converts int to byte[]

private static byte[] intToBytes(int i)
{

 byte[] integerBs = new byte[MAX_INT_LEN];
 integerBs[0] = (byte) ((i >>> 24) & 0xFF);
 integerBs[1] = (byte) ((i >>> 16) & 0xFF);
 integerBs[2] = (byte) ((i >>> 8) & 0xFF);
 integerBs[3] = (byte) (i & 0xFF);
 return integerBs;
}

Let's say I try to convert the integer 4 to bits:

byte[] lenBs = intToBytes(4);
int a=(int)lenBs[0];
System.out.println("result:"+a);

The value of MAX_INT_LENGTH is 4

I get result:0 for every int that I put as a parameter for the method.Please tell me where i went wrong.Thank you.

Emil Grigore
  • 929
  • 3
  • 13
  • 28

1 Answers1

2

lenBs[0] is just getting:

integerBs[0] = (byte) ((i >>> 24) & 0xFF);

... which in the case of i = 4, integerBs[0] == 0.

David Sainty
  • 1,398
  • 12
  • 10
  • then how should I convert the byte array to int ? a=(int)lenbs[3] ? – Emil Grigore Sep 02 '13 at 13:29
  • 1
    @EmilGrigore: You need to reverse the steps you did when converting the `int` to a `byte[]`. – jlordo Sep 02 '13 at 13:31
  • 1
    I think i found this method that does the trick:java.nio.ByteBuffer.wrap(bytes).getInt(); – Emil Grigore Sep 02 '13 at 13:33
  • No, an integer cast of a byte just casts that byte. I would simply reverse the code in intToBytes(). There are other techniques (E.g. via ByteBuffer), but that would be using two very different styles in the same code. – David Sainty Sep 02 '13 at 13:36
  • @EmilGrigore - I think you will learn more if you stop looking for cut-and-paste solutions, and take the time to *read* and *understand* the code. – Stephen C Sep 02 '13 at 13:38