Link to home
Start Free TrialLog in
Avatar of chinchin
chinchin

asked on

int to byte array conversion

I have a problem with integer to byte conversion. I have  to convert an int to a byte array and then the byte array back to int in java programming. I have looked into various sources but not getting a proper answer. Any help from the experts would be greately appreciated.
Avatar of vemul
vemul

let's say you have

int i;
byte b;

int iconv;
byte bconv;
// convert byte to int
iconv = b & 0xff;
// convert int to byte
bconv = (byte)i


0xff basically corresponds to 255 (so anding it with it returns an int value that has 8 bits.. you could and it with 255 if u are not comfortable with 0xff)

HTH

vemul
Avatar of chinchin

ASKER

Thanks for you reply. Your solution works partially (for integers < 255). If I use integers greater than 255, it gets messed up. Is there a way for me convert int to a byte array for numbers > 255?
Maybe this will help:

int i;

String intStr = Integer.toString(i)
byte[] bytes = intStr.getBytes();

Or you can use:
Integer integer = new Integer(i);
byte b = integer.byteValue();
I still have the same problem. A byte will store only one byte value whereas an int holds 4 bytes. I need a methos of storing it in a byte array. As far as converting to string is concerned, we are not allowed to do that. We have to pass int across the network. Thanks for your help
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
public byte[] intBytes(int intValue)
{
  byte[] bytes=new bytes[4];
  bytes[0]= (byte)((intValue>>> 0)&0xff);
  bytes[1]= (byte)((intValue>>> 8)&0xff);
  bytes[2]= (byte)((intValue>>>16)&0xff);
  bytes[3]= (byte)((intValue>>>24)&0xff);

  return bytes
}
public int bytesInt(byte[] bytes)
{
  return bytes[0]+(bytes[1]<<8)+(bytes[2]<<16)+(bytes[3]<<24);
}
This solution provided me with what I needed. Thank you very much.