• 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;

        }

     

     

     

     

     

     

  • 相关阅读:
    含文档+PPT+源码等]精品基于java开发的航空订票系统SSM[包运行成功]Java毕业设计SSM项目源码
    高效偏振无关透射光栅的分析与设计
    扬帆牧哲:怎样开网店创业?
    c++之类与对象
    hive 3.1.4部署
    【Git】轻松学会 Git(一):掌握 Git 的基本操作
    音频怎么转文字?学会这3招,轻松拉满你的工作效率
    【毕业设计】Yolov安全帽佩戴检测 危险区域进入检测 - 深度学习 opencv
    C++重载运算符的规则
    详解AUTOSAR:什么是AUTOSAR?
  • 原文地址:https://blog.csdn.net/qq_38567039/article/details/126027801