Home > other >  Extract a byte into a specific bit
Extract a byte into a specific bit

Time:12-29

I have one byte of data and from there I have to extract it in the following manner.

data[0] has to extract

id(5 bit)
Sequence(2 bit)
HashAppData(1 bit)

data[1] has to extract

id(6 bit)
offset(2 bit)

Required functions are below where byte array length is 2 and I have to extract to the above manner.

public static int ParseData(byte[] data)
{
       // All code goes here
}

Couldn't find any suitable solution to how do I make it. Can you please extract it?

EDIT: Fragment datatype should be in Integer

CodePudding user response:

Something like this?

    int id = (data[0] >> 3) & 31;
    int sequence = (data[0] >> 1) & 3;
    int hashAppData = data[0] & 1;
    
    int id2 = (data[1] >> 2) & 63;
    int offset = data[1] & 3;

CodePudding user response:

This is how I'd do it for the first byte:

byte value = 155;
byte maskForHighest5 = 128 64 32 16 8;
byte maskForNext2 = 4 2;
byte maskForLast = 1;
byte result1 = (byte)((value & maskForHighest5) >> 3); // shift right 3 bits
byte result2 = (byte)((value & maskForNext2) >> 1); // shift right 1 bit
byte result3 = (byte)(value & maskForLast);

Working demo (.NET Fiddle):
https://dotnetfiddle.net/lNZ9TR

Code for the 2nd byte will be very similar.

  • Related