站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2ME 专题两种将int类型的数据转换成byte数组,以及反向转换的代码

两种将int类型的数据转换成byte数组,以及反向转换的代码

摘要: 两种将int类型的数据转换成byte数组,以及反向转换的代码
<tr><td>
http:///tech/article942.html
[转贴自scent of mobile application]

/**
* 将基本数据类型转换为byte数组,以及反向转换的方法
* 只涉及转换操作,对于参数没有进行校验
* 适用范围:RMS操作、网络数据传输
*/
public class DataConvert{
/**
* 将int类型的数据转换为byte数组
* @param n int数据
* @return 生成的byte数组
*/
public static byte[] intToBytes(int n){
String s = String.valueOf(n);
return s.getBytes();
}

/**
* 将byte数组转换为int数据
[] * @param b 字节数组
* @return 生成的int数据
*/
public static int bytesToInt(byte[] b){
String s = new String(b);
return Integer.parseInt(s);
}

/**
* 将int类型的数据转换为byte数组
* 原理:将int数据中的四个byte取出,分别存储
* @param n int数据
* @return 生成的byte数组
*/
public static byte[] intToBytes2(int n){
byte[] b = new byte[4];
for(int i = 0;i < 4;i++){
b[i] = (byte)(n >> (24 - i * 8));
}
return b;
}

/**
* 将byte数组转换为int数据
* @param b 字节数组
* @return 生成的int数据
*/
[] public static int byteToInt2(byte[] b){
return (((int)b[0]) << 24) + (((int)b[1]) << 16) + (((int)b[2]) << 8) + b[3];
}
}
http:///tech/article942.html
</td></tr></table></td> </tr> <tr> <td background="/pic/split.gif" height=1></td> </tr> <tr> <td class="tdMargin1">
↑返回目录
前一篇: J2ME程序开发全方位基础讲解汇总--J2ME 3D编程的一些资料
后一篇: J2ME编程之Nokia 7210配置篇