java int轉byte和long轉byte,intbyte

來源:互聯網
上載者:User

java int轉byte和long轉byte,intbyte

在網路編程中,出於節約頻寬或者編碼的需要,通常需要以原生方式處理long和int,而不是轉換為string。

public class ByteOrderUtils {

public static byte[] int2byte(int res) {
byte[] targets = new byte[4];

targets[3] = (byte) (res & 0xff);// 最低位
targets[2] = (byte) ((res >> 8) & 0xff);// 次低位
targets[1] = (byte) ((res >> 16) & 0xff);// 次高位
targets[0] = (byte) (res >>> 24);// 最高位,無符號右移。
return targets;
}

public static int byteArrayToInt(byte[] b){
byte[] a = new byte[4];
int i = a.length - 1,j = b.length - 1;
for (; i >= 0 ; i--,j--) {//從b的尾部(即int值的低位)開始copy資料
if(j >= 0)
a[i] = b[j];
else
a[i] = 0;//如果b.length不足4,則將高位補0
}
int v0 = (a[0] & 0xff) << 24;//&0xff將byte值無差異轉成int,避免Java自動型別提升後,會保留高位的符號位
int v1 = (a[1] & 0xff) << 16;
int v2 = (a[2] & 0xff) << 8;
int v3 = (a[3] & 0xff) ;
return v0 + v1 + v2 + v3;
}

public static byte[] long2byte(long res) {
byte[] buffer = new byte[8];
for (int i = 0; i < 8; i++) {
int offset = 64 - (i + 1) * 8;
buffer[i] = (byte) ((res >> offset) & 0xff);
}
return buffer;
}

public static long byteArrayToLong(byte[] b){
long values = 0;
for (int i = 0; i < 8; i++) {
values <<= 8; values|= (b[i] & 0xff);
}
return values;
}

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.