zoukankan      html  css  js  c++  java
  • byte数组和int,long之间的互相转换

     public static long byteToLong(byte[] value) {
            long temp = 0;
            for (int i = 0; i < value.length; i++) {
                temp = (temp | value[i]) << 8;
            }
            return temp;
        }
     public static byte[] longToByte(long number) {
            long temp = number;
            byte[] b = new byte[8];
            for (int i = b.length - 1; i >= 0; i--) {
                b[i] = Long.valueOf(temp & 0xff).byteValue();// 将最低位保存在最高位
                temp = temp >> 8; // 向右移8位
            }
            return b;
        }

        public static byte[] intToByte(int number) {
            int temp = number;
            byte[] b = new byte[4];
            for (int i = b.length - 1; i >= 0; i--) {
                b[i] = Integer.valueOf(temp & 0xff).byteValue();// 将最低位保存在最高位
                temp = temp >> 8; // 向右移8位
            }
            return b;
        }


    public static long byteToLong(byte[] value) {
            long temp = 0;
            for (int i = 0; i < value.length; i++) {
                temp = (temp | value[i]) << 8;
            }
            return temp;
        }
    /**
         * byte数组中取int数值,本方法适用于(低位在前,高位在后)的顺序,和和intToBytes()配套使用    
    *      
    * @param src     
    *            byte数组     
    * @param offset     
    *            从数组的第offset位开始     
    * @return int数值     
    */    
    public static int bytesToInt(byte[] src, int offset) {  

        int value;    

        value = (int) ((src[offset] & 0xFF)   

                | ((src[offset+1] & 0xFF)<<8)   

                | ((src[offset+2] & 0xFF)<<16)   

                | ((src[offset+3] & 0xFF)<<24));  return value;  

    }  

    1. /**  
    2.     * byte数组中取int数值,本方法适用于(低位在后,高位在前)的顺序。和intToBytes2()配套使用 
    3.     */  
    4. public static int bytesToInt2(byte[] src, int offset) {  
    5.     int value;    
    6.     value = (int) ( ((src[offset] & 0xFF)<<24)  
    7.             |((src[offset+1] & 0xFF)<<16)  
    8.             |((src[offset+2] & 0xFF)<<8)  
    9.             |(src[offset+3] & 0xFF));  
    10.   return value;  
      1. public static byte[] intToByte4(int Num)
      2.   {  
      3.  byte[] abyte=new byte[8]; //int为32位除4位,数组为8   
      4. int j=0xf;    
      5. int z = 4; //转换的位数    
      6. for (int i = 0; i < 8; i++)   
      7. {    
      8. int y = j << z * i;   
      9.  int x = Num & y;    
      10. x = x >> (z * i);    
      11. abyte[i] = (byte)(x);   
      12. }    
      13. return abyte;  
      14. }
  • 相关阅读:
    Mysql索引查询失效的情况
    常用的设计模式
    dubbo的实现原理
    HashMap和HashTable的区别
    SpringMVC工作原理的介绍
    SpringMVC 基础内容及使用步骤
    BeanFactory和ApplicationContext的区别+部分Spring的使用
    Spring常用的jar+普通构造注入
    如何在CentOS7上安装MySQL并实现远程访问
    如何搭建Spring MVC 框架---Hello World
  • 原文地址:https://www.cnblogs.com/ting5/p/5323035.html
Copyright © 2011-2022 走看看