打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
整型int和字符数组byte相互转换的源程序
整型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;
    }
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
Java byte数组转有符号int
c语言考试题
java数据类型转换
这两道题不会?你敢说你精通c语言
Java的常见误区与细节
java,c,c语言之间基本数据类型的比较
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服