java int转byte数组

版权声明:版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_41054313/article/details/88424454

                                各种基本数据类型转byte数组并反转


目录

                                各种基本数据类型转byte数组并反转

 

int 转 byte[]   低字节在前(低字节序)

int 转 byte[]   高字节在前(高字节序)

short 转 byte[] 低字节在前(低字节序)

short 转 byte[] 高字节在前(高字节序)

byte[] 转 int(short类型也一样,返回值改成short即可) 低字节在前(低字节序)

byte[] 转 int(short类型也一样,返回值改成short即可) 高字节在前(高字节序)


int 转 byte[]   低字节在前(低字节序)

public static byte[] toLH(int n) {  
  byte[] b = new byte[4];  
  b[0] = (byte) (n & 0xff);  
  b[1] = (byte) (n >> 8 & 0xff);  
  b[2] = (byte) (n >> 16 & 0xff);  
  b[3] = (byte) (n >> 24 & 0xff);  
  return b;  
}

int 转 byte[]   高字节在前(高字节序)

public static byte[] toHH(int n) {  
  byte[] b = new byte[4];  
  b[3] = (byte) (n & 0xff);  
  b[2] = (byte) (n >> 8 & 0xff);  
  b[1] = (byte) (n >> 16 & 0xff);  
  b[0] = (byte) (n >> 24 & 0xff);  
  return b;  
}

byte[] 转 int 低字节在前(低字节序)

public int toInt(byte[] b){
    int res = 0;
    for(int i=0;i<b.length;i++){
        res += (b[i] & 0xff) << (i*8);
    }
    return res;
}

byte[] 转 int 高字节在前(高字节序)

public static int toInt(byte[] b){
    int res = 0;
    for(int i=0;i<b.length;i++){
        res += (b[i] & 0xff) << ((3-i)*8);
    }
    return res;
}

猜你喜欢

转载自blog.csdn.net/qq_41054313/article/details/88424454