When you want to send an integer through the socket from a Java application to a C application, or your Java application needs to save some integer in the file so the C application will read it, you need to convert one integer (int type ) to 4 bytes ( array of 4 bytes ). Here is a class that does the job:
/** Performs conversions between integer ( long ) and 4 bytes and vice
versa. */
public class IntByteConverter{
private int intValue;
private byte[] byteArray;
public final static int mask = 256;
/** IntByteConverter constructor . */
public IntByteConverter() {
super();
byteArray = new byte[4];
}
/** IntByteConverter constructor. */
public IntByteConverter(int theIntValue) {
super();
intValue = theIntValue;
byteArray = new byte[4];
}
/** Converts 4 bytes array to the int. */
public void bytesToInt()
{
int temp;
int pMask = 1;
intValue = 0;
for( int i = 0; i < 4; i++ )
{
if( byteArray[i] < 0 )
temp = mask+byteArray[i];
else
temp = byteArray[i];
intValue += temp*pMask;
pMask *= mask;
}
}
/** @return byte[] */
public byte[] getBytes() {
return byteArray;
}
/** @return int */
public int getIntValue() {
return intValue;
}
/** Converts the int to 4 bytes array. */
public void intToBytes()
{
int x = intValue;
byte y = 0;
int temp = 0;
for( int i = 0; i < 4; i++ )
{
y = (byte)(x%mask);
if( y < 0 )
{
byteArray[i] = (byte)(mask + y);
temp = x-(mask+y);
}
else
{
byteArray[i] = y;
temp = x-y;
}
x = temp/mask;
}
}
/**
* Starts the application.
* @param args an array of command-line arguments
*/
public static void main(java.lang.String[] args) {
IntByteConverter c = new IntByteConverter( 50 );
c.intToBytes();
c.printBytes();
}
public void printBytes()
{
for( int i = 0; i < 4; i++ )
System.out.print( byteArray[i] + " " );
System.out.println();
}
public void setBytes(byte[] newByteArray)
{
byteArray = newByteArray;
}
public void setInt(int newIntValue)
{
intValue = newIntValue;
}
}