如何发现身边的商机:整型int和字符数组byte相互转换的源程序
来源:百度文库 编辑:偶看新闻 时间:2024/04/29 16:38:14
整型int和字符数组byte相互转换的源程序我目前在做一个有关网络数据流的程序,需要实现整型int和字符数组byte相互转换的功能,在网上搜索时没找到相关文章,最后自己写了一个封装类,把它贴出来,兴许别人能用上。 /**
* Name : ByteIntSwitch.java
*
* Function: get an int, convert it to a byte[];
* get a byte[], convert it to int value;
*
*/public class ByteIntSwitch {
public static void main(String[] args){
Integer itr=new Integer(600000000);
byte[] b=toByteArray(itr.intValue());
int j=toInt(b);
System.out.println(j); }
// 将iSource转为长度为iArrayLen的byte数组,低位是低字节--见代码中举例
// 若低位是高字节,只需for中从高到低递减,而非从低到高递增
public static byte[] toByteArray(int iSource) {
byte[] bLocalArr = new byte[4];
for ( int i = 0; i < 4; i++) {
bLocalArr[i] = (byte)( iSource>>8*i & 0xFF );
}
return bLocalArr;
}
// 将byte数组bRefArr转为一个整数,低位是低字节--见代码中举例
// 若低位是高字节,只需for中从低到高递增,而非从高到低递减
public static int toInt(byte[] bRefArr) {
int iOutcome = 0;
for ( int i = 0; i < 4; i++) {
iOutcome += (bRefArr[i]& 0xFF) << (8 *i) ;
}
return iOutcome;
}
}
* Name : ByteIntSwitch.java
*
* Function: get an int, convert it to a byte[];
* get a byte[], convert it to int value;
*
*/public class ByteIntSwitch {
public static void main(String[] args){
Integer itr=new Integer(600000000);
byte[] b=toByteArray(itr.intValue());
int j=toInt(b);
System.out.println(j); }
// 将iSource转为长度为iArrayLen的byte数组,低位是低字节--见代码中举例
// 若低位是高字节,只需for中从高到低递减,而非从低到高递增
public static byte[] toByteArray(int iSource) {
byte[] bLocalArr = new byte[4];
for ( int i = 0; i < 4; i++) {
bLocalArr[i] = (byte)( iSource>>8*i & 0xFF );
}
return bLocalArr;
}
// 将byte数组bRefArr转为一个整数,低位是低字节--见代码中举例
// 若低位是高字节,只需for中从低到高递增,而非从高到低递减
public static int toInt(byte[] bRefArr) {
int iOutcome = 0;
for ( int i = 0; i < 4; i++) {
iOutcome += (bRefArr[i]& 0xFF) << (8 *i) ;
}
return iOutcome;
}
}
linux gcc下字符转换整型的函数?
有一个BYTE[ 2]的数组,BYTE[0]=0x04.BYTE[1]=0x05,请问我怎样才能将其转换为字符串“0405”?
字符串和字符混合数组的问题?
ASP中数组转换成字符的问题
ASCII与字符间的相互转换如何实现?
谁有二进制码与字符相互转换的源程序?急需
关于C#中string和Byte的转换问题
vb中怎么把INPUTBOX中输入的字符型数字转换成整型数?
输入一行数字字符,用整型数组统计其中每个数字字符的个数,下标为零的元素存放'0'的个数……
vc中如何利用数组将字符串转换为整型
CString与char字符数组怎么样才能相互转化使用?
请问JAVA如何将字符型转换为整型?
char 类型的数组可不可以转为int类型的数组?
整型和短整型的区别是什么?
C#中的Byte类型的数组怎样初始化?
二进制 和 八进制 怎么相互转换的??
求数组int a[n]中奇数的个数和平均数?
求数组int a[n]中奇数的个数和平均数?
字节数组byte[]a,byte[] b都读入了文件内容,要将这两个文件的内容写入到另外一个数组byte[] c里要怎么写
VB数值和字符转换的问题
c#字符数组转字符串的问题
关于 C 语言的字符指针数组
VC7里面为什么两个连续声明的int地址间隔12Byte
C++ 要定义一个数组,这个数组里又有整型元素,又有字符元素,该用什么定义啊?