怎么样用JAVA读取单独的比特出来

来源:百度知道 编辑:UC知道 时间:2024/09/23 05:48:31
我现在在做一个作品 是要从单片机上读数据到PC机上并进行处理 ,现在单片机发到电脑上来的是一个字节,前两位代表起始位,最后两位是终止位,中间四位是数据为,其中前两位是一种数据 后两位是一种数据,请问有没有办法把它们分别读出来呢!!!????谢谢大虾们哦

有办法哦,很简单的读法
如果你可以把这个字节都读出来的话

public class ByteTest {
public static void main(String[] args) {
byte[] buffer = new byte[]{1,2,3,4,5,6};
byte[] beginBytes = new byte[2],endBytes = new byte[2],numberBytes = new byte[2];
//然后分别读取
System.arraycopy(buffer, 0, beginBytes, 0, 2);
System.arraycopy(buffer, 2, numberBytes, 0, 2);
System.arraycopy(buffer, 4, endBytes, 0, 2);

//最后上面三个byte数组就是你想要的数字了
//比如
int number = bytes2int(numberBytes,2);
for(byte b : numberBytes){
System.out.println(b);
}
}

public static int bytes2int(byte[] b, int size) {
int mask = 0xff;
int temp = 0;
int res = 0;
for (int i = 0; i < size; i++) {
res <<= 8;
temp = b[i] & mask;
res |= temp;