Java中byte轉int的方法,javabyte轉int

來源:互聯網
上載者:User

Java中byte轉int的方法,javabyte轉int

byte轉化為int有兩種情況:

1)要保持數值不變

應用情境:數值計算,等等。

方法:可以直接採用強制類型轉換:int i = (int) aByte,

例如:若aByte=0xff(即數值為-1),則轉化為int後,i為0xffffffff,數值仍為-1。


2)保持最低位元組中各個位不變,3個高位元組全部用0填充

應用情境:編解碼操作,

方法:採用位操作:int i = aByte & 0xff,

例如:若aByte=0xff,轉化為int後,i為0x000000ff。


java中int怎轉換byte

因為在java中,int類型的佔4個位元組,而byte佔1個位元組,所以int類型轉化為byte類型時會出現位丟失情況,即將int的低8位作為byte類型的值。int型變數的值為257,對應的二進位是100000001,後8位是00000001,第一個0表示符號位,表示正數,所以變數x的值為1。
 
java中int與byte〔4〕的相互轉換

import java.io.*;

public class IOTest {
public static void main(String[] args) throws Exception {
int i = 65535;
byte[] b = intToByteArray1(i);
for(byte bb : b) {
System.out.print(bb + " ");
}
}

public static byte[] intToByteArray1(int i) {
byte[] result = new byte[4];
result[0] = (byte)((i >> 24) & 0xFF);
result[1] = (byte)((i >> 16) & 0xFF);
result[2] = (byte)((i >> 8) & 0xFF);
result[3] = (byte)(i & 0xFF);
return result;
}

public static byte[] intToByteArray2(int i) throws Exception {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(buf);
out.writeInt(i);
byte[] b = buf.toByteArray();
out.close();
buf.close();
return b;
}
}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.