0

I have a byte b

byte has 8 bits

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

how would I parse bits 3 and 4?

6 Answers 6

2

You can use BitSet class to retrieve specific bits from a byte value:

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;
}

By using the above method, you can get the BitSet representation of your byte and get specific bits:

byte b = ...; // byte value.
System.out.println(fromByte(b).get(2));  // printing bit #3
System.out.println(fromByte(b).get(3));  // printing bit #4
Sign up to request clarification or add additional context in comments.

Comments

2

try

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

2 Comments

Can you explain what the bit anding is doing here and why we are anding it by 0xC. Thanks
full byte may be 0b11001100 or 0b01001100 or other, but after & 0xC it becomes 0b00001100, only bit 3 and 4 are left, and we now we can analize our byte by comparing it with 0000 1000 0100 0000
1
switch ((b>>3)&3){
  case 0: return still;
  case 1: return noStill;
  case 2: return stationed;
  case 3: return slow
}

Comments

1

bitwise AND (&)

Example:

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

2 Comments

can you demonstrate in a small snippet. Thank you greatly
I already did. I am not going to do your code for you. You are welcome.
1

If I get you right, you want the bits in b[3] and b[4] to be parsed like this:

00 = still
01 = noStill
10 = stationed
11 = slow

I'd do this:

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 */}
}

Comments

0

in JBBP it looks like

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.