整型int和字符数组byte相互转换的源程序
我目前在做一个有关网络数据流的程序,需要实现整型int和字符数组byte相互转换的功能,在网上搜索时没找到相关文章,最后自己写了一个封装类,把它贴出来,兴许别人能用上。
/**
* Name : ByteIntSwitch.java
* Date : Created on 2004/11/05 14:40
* Author : ZHUO Bibo
* Function: get an int, convert it to a byte[];
* get a byte[], convert it to int value;
*
* Compiler: Eclipse 3.0
*
*/
/**
* @author ZHUO Bibo
*
*/
public final class ByteIntSwitch {
/*
public static void main(String args[] ) {
int i = 1000;
byte[] b = toByteArray(i, 4);
System.out.println( "1000's bin: " + Integer.toBinaryString(1000));
System.out.println( "1000's hex: " + Integer.toHexString(1000));
}
*/
// 将iSource转为长度为iArrayLen的byte数组,低位是低字节--见代码中举例
// 若低位是高字节,只需for中从高到低递减,而非从低到高递增
public static byte[] toByteArray(int iSource, int iArrayLen) {
byte[] bLocalArr = new byte[iArrayLen];
// Note that an int is 4 bytes long
for ( int i = 0; (i < 4) && (i < iArrayLen); i++) {
bLocalArr[i] = (byte)( iSource>>8*i & 0xFF );
//System.out.print(Integer.toHexString(bLocalArr[i]) + " "); //for
// testing e.g: if 1000==iSource, then result is ffffffe8 03 00 00
}
return bLocalArr;
} // End of 'toByteArray()'
// 将byte数组bRefArr转为一个整数,低位是低字节--见代码中举例
// 若低位是高字节,只需for中从低到高递增,而非从高到低递减
public static int toInt(byte[] bRefArr) {
int iOutcome = 0;
byte bLoop;
for ( int i = bRefArr.length - 1; i >= 0 ; i--) {
bLoop = bRefArr[i];
iOutcome += (bLoop & 0xFF) << (8 * (3 - i));
/*
* The another method is as follow, but the efficiency is low
switch (i) {
case 3: iOutcome += (bLoop & 0xFF)<<24; break;
case 2: iOutcome += (bLoop & 0xFF)<<16; break;
case 1: iOutcome += (bLoop & 0xFF)<<8; break;
case 0: iOutcome += bLoop & 0xFF; break;
}
*/ // System.out.println("iOutcome is: " + iOutcome +
// " bRefArr[" + i + "] is " + bRefArr[i] + " ");
} // End of for loop
return iOutcome;
} // End of 'toInt()'
} // End of 'public class ByteArrToInt '
本文提供了一种在Java中实现整型(int)与字节数组(byte[])互相转换的方法。通过自定义类ByteIntSwitch实现了int到byte[]及byte[]到int的转换,适用于网络数据流等场景。

被折叠的 条评论
为什么被折叠?



