java整數和byte數組之間的轉換

來源:互聯網
上載者:User

做的程式有時候會需要用到,

記錄下

public class NumberUtil {/** * int整數轉換為4位元組的byte數組 *  * @param i *            整數 * @return byte數組 */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整數轉換為8位元組的byte數組 *  * @param lo *            long整數 * @return byte數組 */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整數轉換為2位元組的byte數組 *  * @param s *            short整數 * @return byte數組 */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數群組轉換為無符號short整數 *  * @param bytes *            byte數組 * @return short整數 */public static int byte2ToUnsignedShort(byte[] bytes) {return byte2ToUnsignedShort(bytes, 0);}/** * byte數群組轉換為無符號short整數 *  * @param bytes *            byte數組 * @param off *            開始位置 * @return short整數 */public static int byte2ToUnsignedShort(byte[] bytes, int off) {int high = bytes[off];int low = bytes[off + 1];return (high << 8 & 0xFF00) | (low & 0xFF);}/** * byte數群組轉換為int整數 *  * @param bytes *            byte數組 * @param off *            開始位置 * @return int整數 */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;}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.