在日常的項目中,我們經常會遇到這樣的問題,就是將基本數據類型轉化成字節數據,
其實,字節數組是我們經常使用的,包括文件流,以及socket的數據傳輸,基本都是要求字節數組,雖然大部分人可能都使用應用層協議http,
一般都會使用json作為傳輸格式,但其實底層傳輸層還是將這些數據進行了序列化,因此我們應該熟悉這種基本數據類型和字節數組的轉化。
當然這種應用場景也是非常的多,比如很多時候我們都希望文件的關鍵信息存儲成字節數組,這樣對外不容易解析,雖然存儲成二進制也沒有問題,
但是直接存儲成二進制,在解析上會有一些麻煩,而存儲成字節數據,我們很清楚每4個字節組成一個int,這樣處理起來相對方便一點,不需要認為約定很多東西
下面就是int和byte[]的轉換方式,
public class NumConvert { public static void main(String[] args) { System.out.println(Integer.toBinaryString(257)); System.out.println(bytes2Int(int2Bytes(257))); } /** * 轉化過程一定是高位在前 * @param num * @return */ public static byte[] int2Bytes(int num) { byte[] result = new byte[4]; result[0] = (byte)((num >>> 24) & 0xff); result[1] = (byte)((num >>> 16) & 0xff ); result[2] = (byte)((num >>> 8) & 0xff ); result[3] = (byte)((num >>> 0) & 0xff ); return result; } public static int bytes2Int(byte[] bytes ) { int int1 = (bytes[0]&0xff) << 24; int int2 = (bytes[1]&0xff) << 16; int int3 = (bytes[2]&0xff) << 8; int int4 = (bytes[3]&0xff); return int1|int2|int3|int4; } }