首页 > 解决方案 > 如何从字节数组中复制字节部分?

问题描述

我取了一个字符串,例如“hello”,并将其设为字节数组 (str.getBytes()),现在我想选择一些位,例如 5,17,26,...(最多 4 个字节/32 位)由 8 位字节组成的字节数组并将位选择转换为整数,但我不知道如何......没有什么对我真正有用,我不想使用特殊的库。

我尝试过移位,但我似乎并不真正理解这是如何工作的......虽然它可能是最好的方法

public int[] calcInts(String str) { // str e.g. "hello" or "prhfetg"

byte[] bytes = str.getBytes() // make byte array
selection = 9 // variable - can be greater or smaller than 8 (1 byte)
numOfParts = (str.length*8)/selection  
int[] arr = new int[numOfParts]

for (int i=0; i<numOfParts; i++) { // calculate integers 

// HELP section --> do something with byte array to extract selection

int[i] = (int)... // integer from (max 32bit) selection 
}

return arr;
}

标签: javaarraysbytebitstring

解决方案


推荐阅读