整型int和字符数组byte相互转换的源程序
来源:互联网 发布:淘宝上的冷门小众商品 编辑:程序博客网 时间:2024/04/29 16:25
整型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 '
- 整型int和字符数组byte相互转换的源程序
- 整型int和字节数组byte相互转换
- 整型int和字节数组byte相互转换
- 整型变量(int)与字节数组(byte[])的相互转换
- int和byte数组相互转换
- java中的int类型和byte数组的相互转换
- byte数组和Int之间的相互转换
- Java中字符和byte数组之间的相互转换
- Java中字符和byte数组之间的相互转换
- Java中字符和byte数组之间的相互转换
- C# int和byte的相互转换
- C# int和byte的相互转换
- byte和int相互转换
- 将char字符转换成int整型,字符串与整型之间的相互转换
- java int与byte[]数组的相互转换 补码
- String,int,char,byte[]数组的相互转换
- NSData 与NSString,Byte数组,UIImage,int的相互转换
- bitmap和byte数组的相互转换
- 一篇关于session的好文
- 网络数据流的java处理
- 遍历一个文件夹下的所有文件及文件夹,并进行拷贝(代码)
- 书籍下载
- 必须重新定义第2阶段的改革路径
- 整型int和字符数组byte相互转换的源程序
- 网络数据流接收处理过程分析
- java操作Excel
- 李氏父子商场大斗法波诡云谲
- 转贴:C语言测试:想成为嵌入式程序员应知道的0x10个基本问题
- eWebSoft在线文本编辑器飞鱼修改版问题
- onkeydown事件处理回车后提交表单
- 批处理程序设计教程 2
- 世界有影响的十位算法大师