java中int與byte,以及long與byte之間的轉換

來源:互聯網
上載者:User

轉載請註明出處!

原文連結:http://blog.csdn.net/zgyulongfei/article/details/7738970

做項目時候根據協議在發送網路流的時候需要將所有int及long轉換成byte,因此寫了以下的轉換方法,希望能協助到需要的朋友 ^_^

閑話少說,直接上碼。

public class Utilities {public static byte[] int2Bytes(int num) {byte[] byteNum = new byte[4];for (int ix = 0; ix < 4; ++ix) {int offset = 32 - (ix + 1) * 8;byteNum[ix] = (byte) ((num >> offset) & 0xff);}return byteNum;}public static int bytes2Int(byte[] byteNum) {int num = 0;for (int ix = 0; ix < 4; ++ix) {num <<= 8;num |= (byteNum[ix] & 0xff);}return num;}public static byte int2OneByte(int num) {return (byte) (num & 0x000000ff);}public static int oneByte2Int(byte byteNum) {
                //針對正數的intreturn byteNum > 0 ? byteNum : (128 + (128 + byteNum));}public static byte[] long2Bytes(long num) {byte[] byteNum = new byte[8];for (int ix = 0; ix < 8; ++ix) {int offset = 64 - (ix + 1) * 8;byteNum[ix] = (byte) ((num >> offset) & 0xff);}return byteNum;}public static long bytes2Long(byte[] byteNum) {long num = 0;for (int ix = 0; ix < 8; ++ix) {num <<= 8;num |= (byteNum[ix] & 0xff);}return num;}}

public class TestMain {public static void main(String[] args) {int num = 129;System.out.println("測試的int值為:" + num);byte[] int2bytes = Utilities.int2Bytes(num);System.out.printf("int轉成bytes: ");for (int i = 0; i < 4; ++i) {System.out.print(int2bytes[i] + " ");}System.out.println();int bytes2int = Utilities.bytes2Int(int2bytes);System.out.println("bytes轉行成int: " + bytes2int);byte int2OneByte = Utilities.int2OneByte(num);System.out.println("int轉行成one byte: " + int2OneByte);int oneByte2Int = Utilities.oneByte2Int(int2OneByte);System.out.println("one byte轉行成int: " + oneByte2Int);System.out.println();long longNum = 100000;System.out.println("測試的long值為:" + longNum);byte[] long2Bytes = Utilities.long2Bytes(longNum);System.out.printf("long轉行成bytes: ");for (int ix = 0; ix < long2Bytes.length; ++ix) {System.out.print(long2Bytes[ix] + " ");}System.out.println();long bytes2Long = Utilities.bytes2Long(long2Bytes);System.out.println("bytes轉行成long: " + bytes2Long);}}

測試結果如下:

測試的int值為:156int轉成bytes: 0 0 0 -100 bytes轉行成int: 156int轉行成one byte: -100one byte轉行成int: 156測試的long值為:100000long轉行成bytes: 0 0 0 0 0 1 -122 -96 bytes轉行成long: 100000

聯繫我們

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