整型int和字符数组byte相互转换的源程序

本文提供了一种在Java中实现整型(int)与字节数组(byte[])互相转换的方法。通过自定义类ByteIntSwitch实现了int到byte[]及byte[]到int的转换,适用于网络数据流等场景。

整型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 '

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值