dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language:
Expertise: Beginner
Nov 9, 2001

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


Send an Integer through the Socket From a Java application to a C Application


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;	
}

}
Victor Trakhtenberg
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date