• Java:Bytes转short、int、long


    Java:Bytes转short、int、long

    bytes转short、int、long

    /**
      * @description bytes转short
      */
    public static short bytesToShort(byte[] b) {  
        short s = 0;  
        short s0 = (short) (b[0] & 0xff);// 最低位  
        short s1 = (short) (b[1] & 0xff);  
        s0 <<= 8;
        s = (short) (s0 | s1);  
        return s;  
    }
    /** * @description bytes转int */ public static int byteArrayToInt_2(byte[] b) { return b[1] & 0xFF | (b[0] & 0xFF) << 8; } /** * @description bytes转int */ public static int byteArrayToInt(byte[] b) { return b[3] & 0xFF | (b[2] & 0xFF) << 8 | (b[1] & 0xFF) << 16 | (b[0] & 0xFF) << 24; } /** * @description bytes转long */ public static long byteArrayToLongL(byte[] b) {   return b[3] & 0xFFL |    (b[2] & 0xFFL) << 8| (b[1] & 0xFFL) << 16 | (b[0] & 0xFFL) << 24 ; }
    
    
    /**
      * @description bytes转long
      */
    public static long byteArrayToLong8(byte[] b) {
    return (long)b[9] & 0xFF |
    (long)(b[8] & 0xFF) << 8|
    (long)(b[7] & 0xFF) << 16 |
    (long)(b[6] & 0xFF) << 24 |
    (long)(b[5] & 0xFF) << 32|
    (long)(b[4] & 0xFF) << 40|
    (long)(b[3] & 0xFF) << 48 |
    (long)(b[2] & 0xFF) << 56 ;
    }

    short、int、long转bytes

    // long转为4位byte数组
    public static byte[] longToByteArrLen4(long x) {  
        return new byte[] {   
            (byte) ((x >> 24) & 0xFF),   
            (byte) ((x >> 16) & 0xFF),      
            (byte) ((x >> 8) & 0xFF),      
            (byte) (x & 0xFF)   
        };     
    }    
    // int类型转换为长度2的byte数组
    public static byte[] intToByteArray_2(int a) {   
        return new byte[] {        
            (byte) ((a >> 8) & 0xFF),      
            (byte) (a & 0xFF)   
        };   
    } 
    //int类型转换为长度4的byte数组
    public static byte[] intToByteArray(int a) {   
        return new byte[] {   
            (byte) ((a >> 24) & 0xFF),   
            (byte) ((a >> 16) & 0xFF),      
            (byte) ((a >> 8) & 0xFF),      
            (byte) (a & 0xFF)   
        }; 
    }
    //short类型转换长度1的byte
    public static byte shortToByte(short x) {
        byte b = (byte) (0x00FF & x);
        return b;
    }
    //int类型转1位byte
    public static byte intToByte(int a) {   
        return  (byte) (a & 0xFF);
    } 
  • 相关阅读:
    KafkaOffsetMonitor
    锋利的KATANA
    用grunt搭建自动化的web前端开发环境
    网上书店订单功能的实现
    作用域和控制器
    使用CLK.AspNet.Identity提供以角色为基础的访问控制(RBAC)
    ABP日志管理
    .NET开源项目
    服务总线
    Message解析流程(转)
  • 原文地址:https://www.cnblogs.com/lizm166/p/15807560.html
Copyright © 2020-2023  润新知