1. 程式人生 > >byte 常用 操作

byte 常用 操作

exceptio cat 移動 ror 位置 all const 長度 ear

/** * 低位在前,高位在後 * * @param data * @return */ private byte[] intToBytes(int value) { byte[] src = new byte[4]; src[3] = (byte) ((value >> 24) & 0xFF); src[2] = (byte) ((value >> 16) & 0xFF); src[1] = (byte) ((value >> 8) & 0xFF); src[0] = (byte) (value & 0xFF); return src; } public int bytesToInt(byte[] src) { int value; value = (int) ((src[0] & 0xFF) | ((src[1] & 0xFF)<<8) | ((src[2] & 0xFF)<<16) | ((src[3] & 0xFF)<<24)); return value; } /** * 對象轉byte * * @param obj * @return */ public byte[] objectToByte(Object obj) { byte[] bytes = null; ByteArrayOutputStream byteOutput = null; ObjectOutputStream objOutput = null; try { // object to bytearray byteOutput = new ByteArrayOutputStream(); objOutput = new ObjectOutputStream(byteOutput); objOutput.writeObject(obj); bytes = byteOutput.toByteArray(); byteOutput.close(); objOutput.close(); } catch (Exception e) { logger.error("ObjectToByte異常", e); } finally { try { if (byteOutput != null) { byteOutput.close(); } if (objOutput != null) { objOutput.close(); } } catch (IOException e) { logger.error("ObjectToByte異常", e); } } return bytes; } /** * byte 轉對象 * * @param bytes * @return */ public Object byteToObject(byte[] bytes) throws Exception { Object obj = null; ByteArrayInputStream byteInput = null; ObjectInputStream objectInput = null; try { // bytearray to object if (bytes != null) { byteInput = new ByteArrayInputStream(bytes); objectInput = new ObjectInputStream(byteInput); obj = objectInput.readObject(); byteInput.close(); objectInput.close(); } } catch (Exception e) { logger.error("ByteToObject異常", e); throw e; } finally { try { if (byteInput != null) { byteInput.close(); } if (objectInput != null) { objectInput.close(); } } catch (IOException e) { logger.error("byteToObject異常", e); } } return obj; } public byte[] streamToBytes(InputStream inputStream, int len) { /** * inputStream.read(要復制到得字節數組,起始位置下標,要復制的長度) * 該方法讀取後input的下標會自動的後移,下次讀取的時候還是從上次讀取後移動到的下標開始讀取 所以每次讀取後就不需要在制定起始的下標了 */ byte[] bytes = new byte[len]; try { inputStream.read(bytes, 0, len); } catch (IOException e) { logger.error(ConstantUtils.LOG_EXCEPTION, e); } return bytes; }

byte 常用 操作