• 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);
    } 
  • 相关阅读:
    程序打印的日志哪里去了?结合slf4j来谈谈面向接口编程的重要性
    vue项目用npm安装sass包遇到的问题及解决办法
    nginx反向代理配置及常见指令
    你以为你以为的就是你以为的吗?记一次服务器点对点通知的联调过程
    jeecg逆向工程代码的生成及常见问题
    java注解
    终于有了,史上最强大的数据脱敏处理算法
    SpringBoot项目下的JUnit测试
    递归方法
    练习题
  • 原文地址:https://www.cnblogs.com/lizm166/p/15807560.html
Copyright © 2020-2023  润新知