您的位置:首页 > 编程语言 > Java开发

java中byte与int互转

2015-06-09 14:45 288 查看
package com.yl.common.utils;

/**

* byte转换工具

*

* @author huangzp

* @date 2015-6-09

*/

public

class ByteUtil {

/**

* 将iSource转为长度为iArrayLen的byte数组,字节数组的低位是整型的低字节位

* @param iSource

* @param iArrayLen

* @return

*/

public

static byte[] toByteArray(int iSource, int iArrayLen) {
byte

[] bLocalArr = new byte[iArrayLen];
for

(int i = 0; (i < 4) && (i < iArrayLen); i++) {
bLocalArr[i] = (byte

) (iSource >> 8 * i & 0xFF);

}

return

bLocalArr;
}

/**

* 将byte数组bRefArr转为一个整数,字节数组的低位是整型的低字节位

* @param bRefArr

* @return

*/

public

static int toInt(byte[] bRefArr) {
int

iOutcome = 0;
byte

bLoop;

for

(int i = 0; i < 4; i++) {
bLoop = bRefArr[i];

iOutcome += (bLoop & 0xFF

) << (8 * i);

}

return

iOutcome;
}

}

package

com.yl.common.utils;

/**

* byte转换工具

*

* @author huangzp

* @date 2015-6-09

*/

public

class ByteUtil {

/**

* 将iSource转为长度为iArrayLen的byte数组,字节数组的低位是整型的低字节位

* @param iSource

* @param iArrayLen

* @return

*/

public

static byte[] toByteArray(int iSource, int iArrayLen) {
byte

[] bLocalArr = new byte[iArrayLen];
for

(int i = 0; (i < 4) && (i < iArrayLen); i++) {
bLocalArr[i] = (byte

) (iSource >> 8 * i & 0xFF);

}

return

bLocalArr;
}

/**

* 将byte数组bRefArr转为一个整数,字节数组的低位是整型的低字节位

* @param bRefArr

* @return

*/

public

static int toInt(byte[] bRefArr) {
int

iOutcome = 0;
byte

bLoop;

for

(int i = 0; i < 4; i++) {
bLoop = bRefArr[i];

iOutcome += (bLoop & 0xFF

) << (8 * i);

}

return

iOutcome;
}

}

原文地址 http://techfoxbbs.com/blog-1-5.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: