Java解析字节
我有一个字节b 字节有8位Java解析字节,java,byte,Java,Byte,我有一个字节b 字节有8位 bits for single byte 0 = status 1 = locale 2 = AUX bits (3 & 4) relay 1. 0 (hence 00) still 2. 1 (hence 01) noStill 3. 2 (hence 10) stationed 4. 3 (hence 11) slow 5 = message; 6 = stuff 7 = moreStuff 如何解析第3位和第4位?按位和& 例如: myBy
bits for single byte
0 = status
1 = locale
2 = AUX
bits (3 & 4) relay
1. 0 (hence 00) still
2. 1 (hence 01) noStill
3. 2 (hence 10) stationed
4. 3 (hence 11) slow
5 = message;
6 = stuff
7 = moreStuff
如何解析第3位和第4位?按位和&
例如:
myByte & 0x08 --> myByte & 00001000 --> 0 if and only if bit 4 of "myByte" is 0; 0x08 otherwise
可以使用BitSet类从字节值检索特定位:
public static BitSet fromByte(byte b)
{
BitSet bits = new BitSet(8);
for (int i = 0; i < 8; i++)
{
bits.set(i, (b & 1) == 1);
b >>= 1;
}
return bits;
}
试一试
如果我没弄错的话,您希望b[3]和b[4]中的位被解析如下:
00 = still
01 = noStill
10 = stationed
11 = slow
我会这样做:
if(b[3] == 0) { // still or noStill
if(b[4] == 0) {/* still */}
if(b[4] == 1) {/* noStill */}
}
if(b[3] == 1) { // stationed or slow
if(b[4] == 0) {/* stationed */}
if(b[4] == 1) {/* slow */}
}
在里面看起来像
@Bin(type = BinType.BIT) class Parsed { byte status; byte locale; byte aux; byte relay; byte message; byte stuff; byte moreStuff;}
final Parsed parsed = JBBPParser.prepare("bit status; bit locale; bit aux; bit:2 relay; bit message; bit stuff; bit moreStuff;").parse(new byte[]{12}).mapTo(Parsed.class);
你能用一个小片段来演示吗。谢谢你,我已经做了。我不会为你编写代码。不客气。您能解释一下位anding在这里做什么,以及为什么我们要用0xC进行anding吗。Thanksfull字节可能是0b11001100或0b01001100或其他,但在&0xC之后它变成0b00001100,只剩下第3位和第4位,现在我们可以通过将其与0000 1000 0100 0000进行比较来分析字节
if(b[3] == 0) { // still or noStill
if(b[4] == 0) {/* still */}
if(b[4] == 1) {/* noStill */}
}
if(b[3] == 1) { // stationed or slow
if(b[4] == 0) {/* stationed */}
if(b[4] == 1) {/* slow */}
}
switch ((b>>3)&3){
case 0: return still;
case 1: return noStill;
case 2: return stationed;
case 3: return slow
}
@Bin(type = BinType.BIT) class Parsed { byte status; byte locale; byte aux; byte relay; byte message; byte stuff; byte moreStuff;}
final Parsed parsed = JBBPParser.prepare("bit status; bit locale; bit aux; bit:2 relay; bit message; bit stuff; bit moreStuff;").parse(new byte[]{12}).mapTo(Parsed.class);