java int轉byte數組


int 轉 byte[]   低字節在前(低字節序)

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

int 轉 byte[]   高字節在前(高字節序)

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

byte[] 轉 int 低字節在前(低字節序)

1 public int toInt(byte[] b){
2     int res = 0;
3     for(int i=0;i<b.length;i++){
4         res += (b[i] & 0xff) << (i*8);
5     }
6     return res;
7 }

byte[] 轉 int 高字節在前(高字節序)

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM