在通讯中经常需要将数值转换成字节流,或者是将字节流转换成数值。下面提供的程序可以进行int和byte array之间的转换。
在以后一段时间内还将编制浮点数和双精度浮点数与字节流之间的转换程序并与大家分享。欢迎测试和提出意见。
/**
*
* IntConverter
*
* This class provides methods to convert int into byte array and
* byte array back into int.
*
*/
public class IntConverter
{
/**
*
* Method converting int into byte array.
*
* @param number The int value to be converted.
*
*/
public static byte[] toByteArray(int number)
{
int temp = number;
byte[] b=new byte[4];
for (int i = b.length - 1; i -1; i--)
{
b[i] = new Integer(temp & 0xff).bytevalue();
temp = temp 8;
}
return b;
}
/**
*
* Method converting byte array into int.
*
* @param The byte array to be converted.
*
*/
public static int toInteger(byte[] b)
{
int s = 0;
for (int i = 0; i < 3; i++)
{
if (b[i] 0)
s = s + b[i];
else
s = s + 256 + b[i];
s = s * 256;
}
if (b[3] 0)
s = s + b[3];
else
s = s + 256 + b[3];
return s;
}
// Testing program.
public static void main(String[] args)
{
IntConverter abc = new IntConverter();
int s = -1121115678;
byte[] b = abc.toByteArray(s);
for (int i = 0; i <= 3; i++)
System.out.println(b[i]);
s = abc.toInteger(b);
System.out.println(s);
}
}