• Java数组截取如何实现?Java语言教程


    public static int[] arraySub(int[] data, int start, int end)

        {

            int[] C = new int[end - start]; //新建数组C长度为start-end

            int j = 0;

            for (int i = start; i < end; i++)

            {

                < p = "" >

                    C[j] = data[i];

                j++;

            }

            return C; //返回截取数组的地址

        }

     

     

    只能从头截取返回新数组

    Arrays.copyOf(当前数组,截取下标)

     

     

    int 转换为 byte[]

          这个实现起来比较简单,先保存最低的 8 位到 byte 数组中,然后不断的右移 8 位,每次保存低 8 位数据即可,参考代码:(这里包含一个 int 到 byte 的转换,转换规则是截取 int 的最低 8 位作为 byte 值)

        public static byte[] intToBytes(int a){

            byte[] ans=new byte[4];

            for(int i=0;i<4;i++)

                ans[i]=(byte)(a>>(i*8));//截断 int 的低 8 位为一个字节 byte,并存储起来

            return ans;

        }

     

    byte[] 转换为 int

          这个实现起来也比较简单, 每次将 byte 值保存到 int 的最低 8 位,然后 int 左移 8 位,继续保存新的 byte 值即可,参考代码:

       

      

     

     

        public static int bytesToInt(byte[] a){

            int ans=0;

            for(int i=0;i<4;i++){

                ans<<=8;

                ans|=(a[3-i]&0xff);

                /* 这种写法会看起来更加清楚一些:

                int tmp=a[3-i];

                tmp=tmp&0x000000ff;

                ans|=tmp;*/

                intPrint(ans);

            }

            return ans;

        }

        

        public static void main(String[] args) {

            int c=968523,d=-65423;

            byte[] ans=intToBytes(c);

            intPrint(c);

            for(int i=0;i<4;i++)

                bytePrint(ans[i]);

     

            int e=bytesToInt(ans);

            return;

        }

     

     

     

     

     

     

  • 相关阅读:
    后端面经学习自测(一)
    第三章:使用Vue脚手架
    注册阿里云账号,免费领取云服务器!
    微服务系统架构的演变
    VTK ImageData 与ITK、SimpleITK
    嵌入式算法19---国家商用密码SM算法
    【并发编程】线程池及Executor框架
    阿里 P7 到底是怎样的水平?
    【MySQL | 进阶篇】01、存储引擎
    Python爬虫(二十四)_selenium案例:执行javascript脚本
  • 原文地址:https://blog.csdn.net/qq_38567039/article/details/126027801