java中int与byte的相互转换

举报
ShaderJoy 发表于 2021/12/31 22:18:06 2021/12/31
【摘要】 我们都知道,JAVA中的基本数据类型有int,byte,char,long,float,double...,它们与引用数据类型很不一样,之所有在如此面向对象的JAVA语言中依然支持这些值类型,就是考虑到性能的原因。现在,同样是因为考虑到性能,我们需要一种高效的方法使int与byte[]能够自由的相互转换,理由就是,我们需要在网络上传送数...

简单 DataOutputStream ByteArrayOutputStream

      int i = 0;
      ByteArrayOutputStream boutput = new ByteArrayOutputStream();
      DataOutputStream doutput = new DataOutputStream(boutput);
      doutput.writeInt(i);
      byte[] buf = boutput.toByteArray();
  
 

执行相反的过程我们就可以将byte[]->int,我们要用到DataInputStreamByteArrayInputStream


      byte[] buf = new byte[4];
      ByteArrayInputStream bintput = new ByteArrayInputStream(buf);
      DataInputStream dintput = new DataInputStream();
      int i = dintput.readInt();
  
 

下面还有更加高效的方法,虽然看起来会比较费劲一些,但是性能的提升是显而易见的。

注:numberOfLeadingZeros(int i) 在指定 int 值的二进制补码表示形式中最高位(最左边)的 1 位之前,返回零位的数量


      //int -> byte[]
      privatebyte[] intToByteArray(final int integer) {
      int byteNum = (40 -Integer.numberOfLeadingZeros (integer < 0 ? ~integer : integer))/ 8;
      byte[] byteArray = new byte[4];
      for (int n = 0; n < byteNum; n++)
      byteArray[3 - n] = (byte) (integer>>> (n * 8));
      return (byteArray);
      }
      //byte[] -> int
      public static int byteArrayToInt(byte[] b, int offset) {
            int value= 0;
            for (int i = 0; i < 4; i++) {
                int shift= (4 - 1 - i) * 8;
                 value +=(b[i + offset] & 0x000000FF) << shift;
             }
            return value;
       }
  
 


      import java.io.*;
      public class IOTest {
      public static void main(String[] args) throws Exception {
        int i = 65535;
        byte[] b = intToByteArray1(i);
        for(byte bb : b) {
         System.out.print(bb + " ");
        }
      }
      public static byte[] intToByteArray1(int i) {
        byte[] result = new byte[4];
        result[0] = (byte)((i >> 24) & 0xFF);
        result[1] = (byte)((i >> 16) & 0xFF);
        result[2] = (byte)((i >> 8) & 0xFF);
        result[3] = (byte)(i & 0xFF);
        return result;
      }
      public static byte[] intToByteArray2(int i) throws Exception {
        ByteArrayOutputStream buf = new ByteArrayOutputStream();
        DataOutputStream out = new DataOutputStream(buf);
        out.writeInt(i);
        byte[] b = buf.toByteArray();
        out.close();
        buf.close();
        return b;
      }
  
 




文章来源: panda1234lee.blog.csdn.net,作者:panda1234lee,版权归原作者所有,如需转载,请联系作者。

原文链接:panda1234lee.blog.csdn.net/article/details/8691586

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。