位数组到字节数组 [英] Bit array to Byte array

查看:94
本文介绍了位数组到字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将以下位数组转换为字节数组?

How can i convert the following bit array to a byte array?

int[] bits = new int[]{1, 0, 1, 0, 1, 1, 0, 1, 0, 1};

位应按如下方式映射到字节:

The bits should be mapped to bytes as follows:

1010110101 -> 10101101 01000000 (0xAD 0x40)

推荐答案

public class TestBitToByteEncoder {

    public static void main(String[] args) {
        int[] bits = new int[]{1, 0, 1, 0, 1, 1, 0, 1, 0, 1};
        byte[] bytes = encodeToByteArray(bits);
    }

    private static byte[] encodeToByteArray(int[] bits) {
        byte[] results = new byte[(bits.length + 7) / 8];
        int byteValue = 0;
        int index;
        for (index = 0; index < bits.length; index++) {

            byteValue = (byteValue << 1) | bits[index];

            if (index %8 == 7) {
                results[index / 8] = (byte) byteValue;
            }
        }

        if (index % 8 != 0) {
            results[index / 8] = (byte) byteValue << (8 - (index % 8));
        }

        return results;
    }
}

如果您愿意在字节内以相反的顺序存储位:

If you are happy to store the bits in the opposite order within bytes:

private static byte[] encodeToByteArray(int[] bits) {
    BitSet bitSet = new BitSet(bits.length);
    for (int index = 0; index < bits.length; index++) {
        bitSet.set(index, bits[index] > 0);
    }

    return bitSet.toByteArray();
}

这篇关于位数组到字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆