JAVA中int型数据和byte数组之间的相互转换

http://yk3288.blog.hexun.com/43207862_d.html

 http://ilewen.com/questions/821 

前不久,写了个小程序,主要是使用Java对数字图像进行处理,里面有许多操作都需要进行byte数组到int型数据的相互转换,最初想的到的方法自然是使用移位的方法,可是这么写好像有点不好理解,而其不是很美观,后来在高人的指导下,使用了Java中的一个流对象,感觉十分好用,特贴出来和同志们分享分享。

 

 

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.IOException;

 

/**

 * @author yk3288

 *

 */

public class Test {

 

         public static void main(String[] args) throws IOException{

                  System.out.println("application is start");

                  Test t = new Test();

                  t.converIn();

                  t.converStream();

                  System.out.println("convert is over!");

         }
         /**
	* 用移位吧,代码如下,因为int型式4个字节,byte为1个字节,一个字节8位
 	* 当int型转为byte型时,只截取int型的最后一个字节的数据,因此依次移位0,8,16,24就可以依次将各字节拷贝到byte类型的数组中
          * 使用移位的方式进行转换
          */
public void converIn(){

                  Byte[] b = new Byte[]{0,36,0,54};

                  //左移位

                  int i = b[3].intValue() |

                    b[2].intValue() << 8 | 

                    b[1].intValue() << 16 |

                    b[0].intValue() << 24;

                  System.out.println(i);

                  //右移位

                  byte[] b1 = new byte[]{

                                   (byte)(i >> 24),

                                   (byte)(i >> 16),

                                   (byte)(i >> 8),

                                   (byte)(i >> 0),

                  };

                  output(b1);

         }

         

         /**

          * 使用Java中流的操作进行转换

          * 

          * @throws IOException

          */

         public void converStream() throws IOException{

                  DataInputStream dis = new DataInputStream(

                                   new ByteArrayInputStream(new byte[]{0,36,0,54}));

                  int i = dis.readInt();

                  System.out.println(i);

                  ByteArrayOutputStream baos = new ByteArrayOutputStream();

                  DataOutputStream dos = new DataOutputStream(baos);

                  dos.writeInt(i);

                  byte[] b = baos.toByteArray();

                  output(b);

         }

         

         

         /**

          * 输出byte数组

          * 

          * @param b

          */

         public void output(byte[] b){

           for(int i = 0;i < b.length;i++){

                    System.out.print(b[i] + "/" );

           }

           System.out.println();

         }

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值