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.
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();
int i;
String intStr = Integer.toString(i)
byte[] bytes = intStr.getBytes();
Or you can use:
Integer integer = new Integer(i);
byte b = integer.byteValue();
ASKER
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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)&0xf f);
bytes[3]= (byte)((intValue>>>24)&0xf f);
return bytes
}
public int bytesInt(byte[] bytes)
{
return bytes[0]+(bytes[1]<<8)+(by tes[2]<<16 )+(bytes[3 ]<<24);
}
{
byte[] bytes=new bytes[4];
bytes[0]= (byte)((intValue>>> 0)&0xff);
bytes[1]= (byte)((intValue>>> 8)&0xff);
bytes[2]= (byte)((intValue>>>16)&0xf
bytes[3]= (byte)((intValue>>>24)&0xf
return bytes
}
public int bytesInt(byte[] bytes)
{
return bytes[0]+(bytes[1]<<8)+(by
}
ASKER
This solution provided me with what I needed. Thank you very much.
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