1. 程式人生 > >基本類型的相互轉換

基本類型的相互轉換

enum bsp ati main pos 測試的 string color test

 1 public class Utilities {
 2     public static byte[] int2Bytes(int num) {
 3         byte[] byteNum = new byte[4];
 4         for (int ix = 0; ix < 4; ++ix) {
 5             int offset = 32 - (ix + 1) * 8;
 6             byteNum[ix] = (byte) ((num >> offset) & 0xff);
 7         }
 8         return
byteNum; 9 } 10 11 public static int bytes2Int(byte[] byteNum) { 12 int num = 0; 13 for (int ix = 0; ix < 4; ++ix) { 14 num <<= 8; 15 num |= (byteNum[ix] & 0xff); 16 } 17 return num; 18 } 19 20 public static byte int2OneByte(int
num) { 21 return (byte) (num & 0x000000ff); 22 } 23 24 public static int oneByte2Int(byte byteNum) { 25 //針對正數的int 26 return byteNum > 0 ? byteNum : (128 + (128 + byteNum)); 27 } 28 29 public static byte[] long2Bytes(long num) { 30 byte[] byteNum = new
byte[8]; 31 for (int ix = 0; ix < 8; ++ix) { 32 int offset = 64 - (ix + 1) * 8; 33 byteNum[ix] = (byte) ((num >> offset) & 0xff); 34 } 35 return byteNum; 36 } 37 38 public static long bytes2Long(byte[] byteNum) { 39 long num = 0; 40 for (int ix = 0; ix < 8; ++ix) { 41 num <<= 8; 42 num |= (byteNum[ix] & 0xff); 43 } 44 return num; 45 } 46 }
 1 public class TestMain {
 2     public static void main(String[] args) {
 3         int num = 129;
 4         System.out.println("測試的int值為:" + num);
 5 
 6         byte[] int2bytes = Utilities.int2Bytes(num);
 7         System.out.printf("int轉成bytes: ");
 8         for (int i = 0; i < 4; ++i) {
 9             System.out.print(int2bytes[i] + " ");
10         }
11         System.out.println();
12 
13         int bytes2int = Utilities.bytes2Int(int2bytes);
14         System.out.println("bytes轉行成int: " + bytes2int);
15 
16         byte int2OneByte = Utilities.int2OneByte(num);
17         System.out.println("int轉行成one byte: " + int2OneByte);
18 
19         int oneByte2Int = Utilities.oneByte2Int(int2OneByte);
20         System.out.println("one byte轉行成int: " + oneByte2Int);
21         System.out.println();
22 
23         long longNum = 100000;
24         System.out.println("測試的long值為:" + longNum);
25 
26         byte[] long2Bytes = Utilities.long2Bytes(longNum);
27         System.out.printf("long轉行成bytes: ");
28         for (int ix = 0; ix < long2Bytes.length; ++ix) {
29             System.out.print(long2Bytes[ix] + " ");
30         }
31         System.out.println();
32 
33         long bytes2Long = Utilities.bytes2Long(long2Bytes);
34         System.out.println("bytes轉行成long: " + bytes2Long);
35     }
36 }

測試結果:

1 測試的int值為:156
2 int轉成bytes: 0 0 0 -100 
3 bytes轉行成int: 156
4 int轉行成one byte: -100
5 one byte轉行成int: 156
6 
7 測試的long值為:100000
8 long轉行成bytes: 0 0 0 0 0 1 -122 -96 
9 bytes轉行成long: 100000

基本類型的相互轉換