栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java byte数组与int,long,short,byte的转换实现方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java byte数组与int,long,short,byte的转换实现方法

实例如下:

public class DataTypeChangeHelper { 
   
  public static int unsignedByteToInt(byte b) { 
    return (int) b & 0xFF; 
  } 
 
   
  public static String byteToHex(byte b) { 
    int i = b & 0xFF; 
    return Integer.toHexString(i); 
  } 
 
   
  public static long unsigned4BytesToInt(byte[] buf, int pos) { 
    int firstByte = 0; 
    int secondByte = 0; 
    int thirdByte = 0; 
    int fourthByte = 0; 
    int index = pos; 
    firstByte = (0x000000FF & ((int) buf[index])); 
    secondByte = (0x000000FF & ((int) buf[index + 1])); 
    thirdByte = (0x000000FF & ((int) buf[index + 2])); 
    fourthByte = (0x000000FF & ((int) buf[index + 3])); 
    index = index + 4; 
    return ((long) (firstByte << 24 | secondByte << 16 | thirdByte << 8 | fourthByte)) & 0xFFFFFFFFL; 
  } 
 
   
  public static byte[] shortToByteArray(short s) { 
    byte[] targets = new byte[2]; 
    for (int i = 0; i < 2; i++) { 
      int offset = (targets.length - 1 - i) * 8; 
      targets[i] = (byte) ((s >>> offset) & 0xff); 
    } 
    return targets; 
  } 
 
   
  public static byte[] intToByteArray(int s) { 
    byte[] targets = new byte[2]; 
    for (int i = 0; i < 4; i++) { 
      int offset = (targets.length - 1 - i) * 8; 
      targets[i] = (byte) ((s >>> offset) & 0xff); 
    } 
    return targets; 
  } 
 
   
  public static byte[] longToByteArray(long s) { 
    byte[] targets = new byte[2]; 
    for (int i = 0; i < 8; i++) { 
      int offset = (targets.length - 1 - i) * 8; 
      targets[i] = (byte) ((s >>> offset) & 0xff); 
    } 
    return targets; 
  } 
 
   
  public static byte[] int2byte(int res) { 
    byte[] targets = new byte[4]; 
    targets[0] = (byte) (res & 0xff);// 最低位 
    targets[1] = (byte) ((res >> 8) & 0xff);// 次低位 
    targets[2] = (byte) ((res >> 16) & 0xff);// 次高位 
    targets[3] = (byte) (res >>> 24);// 最高位,无符号右移。 
    return targets; 
  } 
 
   
  public static int byte2int(byte[] res) { 
    // res = InversionByte(res); 
    // 一个byte数据左移24位变成0x??000000,再右移8位变成0x00??0000 
    int targets = (res[0] & 0xff) | ((res[1] << 8) & 0xff00); // | 表示安位或 
    return targets; 
  } 
} 

以上就是小编为大家带来的java byte数组与int,long,short,byte的转换实现方法全部内容了,希望大家多多支持考高分网~

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/148996.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号