java整數(shù)與byte數(shù)組的轉(zhuǎn)換實現(xiàn)代碼
湞江網(wǎng)站建設(shè)公司創(chuàng)新互聯(lián),湞江網(wǎng)站設(shè)計制作,有大型網(wǎng)站制作公司豐富經(jīng)驗。已為湞江上千多家提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\外貿(mào)網(wǎng)站制作要多少錢,請找那個售后服務(wù)好的湞江做網(wǎng)站的公司定做!
這里對java中整數(shù)與byte數(shù)組的轉(zhuǎn)換進(jìn)行了實現(xiàn),平時的項目中很少用的到,但是特定需求的時候還是需要的,這里就記錄下,親測可用,
實現(xiàn)代碼:
public class NumberUtil { /** * int整數(shù)轉(zhuǎn)換為4字節(jié)的byte數(shù)組 * * @param i * 整數(shù) * @return byte數(shù)組 */ public static byte[] intToByte4(int i) { byte[] targets = new byte[4]; targets[3] = (byte) (i & 0xFF); targets[2] = (byte) (i >> 8 & 0xFF); targets[1] = (byte) (i >> 16 & 0xFF); targets[0] = (byte) (i >> 24 & 0xFF); return targets; } /** * long整數(shù)轉(zhuǎn)換為8字節(jié)的byte數(shù)組 * * @param lo * long整數(shù) * @return byte數(shù)組 */ public static byte[] longToByte8(long lo) { byte[] targets = new byte[8]; for (int i = 0; i < 8; i++) { int offset = (targets.length - 1 - i) * 8; targets[i] = (byte) ((lo >>> offset) & 0xFF); } return targets; } /** * short整數(shù)轉(zhuǎn)換為2字節(jié)的byte數(shù)組 * * @param s * short整數(shù) * @return byte數(shù)組 */ public static byte[] unsignedShortToByte2(int s) { byte[] targets = new byte[2]; targets[0] = (byte) (s >> 8 & 0xFF); targets[1] = (byte) (s & 0xFF); return targets; } /** * byte數(shù)組轉(zhuǎn)換為無符號short整數(shù) * * @param bytes * byte數(shù)組 * @return short整數(shù) */ public static int byte2ToUnsignedShort(byte[] bytes) { return byte2ToUnsignedShort(bytes, 0); } /** * byte數(shù)組轉(zhuǎn)換為無符號short整數(shù) * * @param bytes * byte數(shù)組 * @param off * 開始位置 * @return short整數(shù) */ public static int byte2ToUnsignedShort(byte[] bytes, int off) { int high = bytes[off]; int low = bytes[off + 1]; return (high << 8 & 0xFF00) | (low & 0xFF); } /** * byte數(shù)組轉(zhuǎn)換為int整數(shù) * * @param bytes * byte數(shù)組 * @param off * 開始位置 * @return int整數(shù) */ public static int byte4ToInt(byte[] bytes, int off) { int b0 = bytes[off] & 0xFF; int b1 = bytes[off + 1] & 0xFF; int b2 = bytes[off + 2] & 0xFF; int b3 = bytes[off + 3] & 0xFF; return (b0 << 24) | (b1 << 16) | (b2 << 8) | b3; } }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!