2012-12-27 86 views
0

我有一個BYTE B的Java字節解析

字節有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?

回答

1
switch ((b>>3)&3){ 
    case 0: return still; 
    case 1: return noStill; 
    case 2: return stationed; 
    case 3: return slow 
} 
1

bitwise AND&

實施例:

myByte & 0x08 --> myByte & 00001000 --> 0 if and only if bit 4 of "myByte" is 0; 0x08 otherwise 
+0

你可以在一個小的片段中演示。非常感謝 – stackoverflow

+0

我已經做到了。我不打算爲你做你的代碼。不用謝。 – SJuan76

2

可以使用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; 
} 

通過使用上面的方法,可以獲得您的字節的BitSet表示並獲取特定位:

byte b = ...; // byte value. 
System.out.println(fromByte(b).get(2)); // printing bit #3 
System.out.println(fromByte(b).get(3)); // printing bit #4 
2

嘗試

boolean still = (b & 0xC) == 0x0; 
    boolean noStill = (b & 0xC) == 0x4; 
    boolean stationed = (b & 0xC) == 0x8; 
    boolean slow = (b & 0xC) == 0xC; 
+0

你能解釋一下在這裏做什麼,以及爲什麼我們用0xC來做這件事。謝謝 – stackoverflow

+1

完整字節可能是0b11001100或0b01001100或其他,但在&0xC之後它變成0b00001100,只留下第3和4位,現在我們可以通過將它與0000 1000 0100 0000 –

+0

進行比較來分析我們的字節。謝謝! – stackoverflow

1

如果我得到你的權利,你想在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 */} 
} 
0

in JBBP它看起來像

@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);