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);
} 
复制代码

 

posted @   整合侠  阅读(1194)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
历史上的今天:
2019-01-15 Spring Boot 2 (八):Spring Boot 集成 Memcached
2019-01-15 Spring Boot 2 (七):Spring Boot 如何解决项目启动时初始化资源
2019-01-15 Spring Boot 2 (六):使用 Docker 部署 Spring Boot 开源软件云收藏
2019-01-15 Spring Boot 2 (五):Docker Compose + Spring Boot + Nginx + Mysql 实践
2019-01-15 Spring Boot 2 (四):使用 Docker 部署 Spring Boot
2019-01-15 Spring Boot 2 (三):Spring Boot 2 相关开源软件
2019-01-15 Spring Boot 2 (二):Spring Boot 2 动态 Banner
点击右上角即可分享
微信分享提示