很多同事工作多年總是搞不清楚對基礎資料型別 (Elementary Data Type)之間轉換操作,其實說到底這些都是小學加減乘除的演算法而已,是理解電腦計算方式的基礎之基礎,今天天氣努熱無比就寫些例子,希望對那些還沒有瞭解同事以知道。
1. 將字串轉換成位元組數組(前兩位元組存放字串長度)
public static byte[] string2Byte(String s){
if(s == null){
return null;
}
byte[] s1 = s.getBytes("utf-8");
if(s1.length > 0xFFFF) {
throw new Exception("字串長度過長。");
}
byte[] b = new byte[s1.length + 2];
b[0] = (byte)((s1.length) >> 8);
b[1] = (byte)((s1.length));
System.arraycopy(s1, 0, b, 2, s1.length);
}
2. 把short型資料轉換為無符號數int(做與操作即可)
public static int covertShort2Integer(short ss) {
return 0x0000FFFF & ss;
}
3. 同理把byte型資料轉換為無符號數int(其他的轉換這裡都是一樣,至於為什麼使用16進位,這和電腦位元組與16進位之間關係有關,這裡不詳述)
public static int coverByte2Integer(byte b) {
return 0x000000FF & b;
}
4. 把int數群組轉換為byte數組(基礎)
public static byte[] coverIntegerArray2ByteArray(int[] s) {
if(s == null || s.length <= 0) {
return null;
}
byte[] buff = new byte[s.length * 4];
for(int i = 0; i < buff.length; i++){
buff[i * 4] = (byte) (s[i] >> 24);
buff[i * 4 + 1] = (byte)(s[i] >> 16);
buff[i * 4 + 2] = (byte)(s[i] >> 8);
buff[i * 4 + 3] = (byte)(s[i]);
}
return buff;
}
5. 如果你真的理解了,可以試著將把byte數群組轉換為int數組,道理是完全一樣,只是一個逆運算。這裡不再寫了。
如果需要可以聯絡我今天就說到這裡。