java byte數組與二進制互相轉換


1.情景展示

在java當中,如何將二進制轉換成byte[]?

如何將byte[]轉換成二進制?

2.具體分析

bit:位/比特,縮寫:b,只能用0或1表示,也就是二進制,每個0或1就是1bit
byte:字節,縮寫:B 1byte=8bits,能夠存儲的數據范圍是-128~+127。
1個字母=1個字節=8bit(8位)
1個數字=1個字節=8bit(8位)
1個漢字=2個字節=16bit(16位)(使用UTF-8字符集,1個漢字=3個字節=24bit)
1 Byte = 8 Bits
1 KB = 1024 Bytes
1 MB = 1024 KB
1 GB = 1024 MB

3.解決方案

二進制轉byte數組

/*
 * bit轉byte
 * @description: 比特轉字節
 * @date: 2022/4/1 10:51
 * @param: bitStr 只能是4位比特或8位比特
 * @return: byte 1個字節
 */
public static byte toByte(String bitStr) {
    if (StringUtils.isEmpty(bitStr)) return 0;
    int re, len;

    len = bitStr.length();

    if (len != 4 && len != 8) return 0;

    if (len == 8) {// 8 bits處理
        if (bitStr.charAt(0) == '0') {// 正數
            re = Integer.parseInt(bitStr, 2);
        } else {// 負數
            re = Integer.parseInt(bitStr, 2) - 256;
        }
    } else {//4 bits處理
        re = Integer.parseInt(bitStr, 2);
    }

    return (byte) re;
}

/*
 * bit轉byte數組
 * @description: 
 * @date: 2022/4/6 10:46
 * @param: bitStr 二進制字符串
 * @return: byte[] 字節數組
 */
@Nullable
public static byte[] toBytes(String bitStr) {
    if (StringUtils.isEmpty(bitStr)) return null;

    int len = bitStr.length();

    if (len % 4 != 0) return null;

    // 當二進制位數不是8位的整數倍時,取整+1;否則,取整
    byte[] bytes = new byte[(int)(Math.ceil(len / 8))];

    int j = 0, k = 0;
    for (int i = 0; i < len; i += 8) {
        j += 8;
        if (j > len) j = len;

        bytes[k] = toByte(bitStr.substring(i,j));
        k++;
    }

    log.debug("二進制轉byte數組:\n{}", ByteUtils.toString(bytes));
    log.debug("二進制長度:{},字節大小:{},比特÷字節={}", bitStr.length(), bytes.length, bitStr.length() / bytes.length);
    return bytes;
}

byte數組轉二進制

/*
 * byte轉bit
 * @description: 字節轉比特
 * 1Byte=8bits
 * @date: 2022/4/1 10:43
 * @param: b 字節
 * @return: java.lang.String 二進制字符串(8位0和1)
 */
@NotNull
@Contract(pure = true)
public static String fromByte(byte b) {

    return "" + (byte) ((b >> 7) & 0x1) +
            (byte) ((b >> 6) & 0x1) +
            (byte) ((b >> 5) & 0x1) +
            (byte) ((b >> 4) & 0x1) +
            (byte) ((b >> 3) & 0x1) +
            (byte) ((b >> 2) & 0x1) +
            (byte) ((b >> 1) & 0x1) +
            (byte) ((b) & 0x1);
}

/*
 * byte[]轉bits
 * @description: 字節數組轉比特字符串
 * @date: 2022/4/1 11:04
 * @param: bytes 字節數組
 * @return: java.lang.String 比特字符串
 * 1byte=8bit
 */
@NotNull
public static String fromBytes(byte[] bytes) {
    if (ByteUtils.isEmpty(bytes)) return "";

    StringBuilder sb = new StringBuilder();
    ByteUtils.toList(bytes).forEach(b -> sb.append(fromByte(b)));

    log.debug("字節數組轉二進制:\n{}", sb);
    log.debug("二進制長度:{},字節大小:{},比特÷字節={}", sb.toString().length(), bytes.length, sb.toString().length() / bytes.length);
    return sb.toString();
}

測試

fromBytes(toBytes("1000000110101110"));

 

寫在最后

  哪位大佬如若發現文章存在紕漏之處或需要補充更多內容,歡迎留言!!!

 相關推薦:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM