整型int和字符數組byte相互轉換的源程序

整型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轉爲長度爲iArrayLenbyte數組,低位是低字節--見代碼中舉例
    // 
若低位是高字節,只需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 '

 

發佈了47 篇原創文章 · 獲贊 2 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章