我有一个字节,我必须将它分成n
位的块并将这些序列放在一个列表中。
示例:
如果n = 2:
byte b = {171}_10 = {1010 1011}_2
--> list = {10, 10, 10, 11}
如果n = 2:
byte b = {108}_10 = {0110 1100}_2
--> list = {01, 10, 11, 00}
如果n = 3:
byte b = {171}_10 = {1010 1011}_2
--> list = {101, 010} -> I removed the last 2 bits
如果n = 3:
byte b = {108}_10 = {0110 1100}_2
--> list = {011, 011} -> I removed the last 2 bits
我该怎么做?
答案 0 :(得分:1)
你可以这样做:
int len=2;
int number=1212;
char[] chars = Integer.toString(number, 2).toCharArray();
String[] strs= new String[(chars.length+len-1)/len];
for(int i=0,j=0;i<chars.length;i+=len,j++)
{
strs[j]=new String(Arrays.copyOfRange(chars,i,i+len));
}
System.out.println(Arrays.toString(strs))
len 变量表示块的长度(您的n)。将您想要的号码设置为数字变量。
答案 1 :(得分:0)
这是一个很容易实现的小例子。
public static void main(String[] args) {
Integer sizeOfChunks = 2;
Integer convertThisToBytes = 1234;
List<String> sequenceOfBitChunks = new ArrayList<String>();
String binaryRepresentation = Integer.toBinaryString(convertThisToBytes);
System.out.println(binaryRepresentation);
for(int i = 0; i + sizeOfChunks <= binaryRepresentation.length(); i = i + sizeOfChunks){
sequenceOfBitChunks.add(binaryRepresentation.substring(i, i + sizeOfChunks));
}
System.out.println(Arrays.toString(sequenceOfBitChunks.toArray()));
}
输出:
10011010010
[10,01,10,10,01]
如果sizeOfChunks = 3
输出变为
10011010010
[100,110,100]