# How to extract bits from binary data

• ### Question

• Hi All,

I would like to extract bits from binary data.

for example:

0001  1100  1110   0101 1010  1111  1111  1010  1001  1100   0000   0001.  . . . . . . . .    (then converted in binary string)

TPR = first bit = 0 (to be skipped, not to be displayed)

GK = the next 3 bits = 001 = (1 shall be displayed)

VGR = the next 5 bits =11001 = 25<sub>dec</sub>  (according to VGR table, 200 shall be displayed)

VZ = the next 5 bits = 11001 = 25<sub>dec</sub> (according to VZ table, 200 shall be displayed)

How to proceed further. Your help is really appreciated.

Thanks and Regards,

Hari

click "Proposed As Answer by" if this post solves your problem or "Vote As Helpful" if a post has been useful to you Happy Programming! Hari

Tuesday, June 30, 2015 9:13 AM

• If the bits are loaded into an array of bytes (for example, using File.ReadAllBytes), then consider the next experimental solution:

byte[] bytes = { 0x1C, 0xE5, /* ... */ };

byte m = 1 << 7;

int i = 0;

Func<int, uint> getNext = ( n ) =>

{

uint r = 0;

while( --n >= 0 )

{

r = ( r << 1 ) | ( ( bytes[i] & m ) == 0 ? 0u : 1u );

if( ( m >>= 1 ) == 0 )

{

m = 1 << 7;

++i;

}

}

return r;

};

uint TPR = getNext( 1 );

uint GK = getNext( 3 );

uint VGR = getNext( 5 );

uint VZ = getNext( 5 );

• Proposed as answer by Tuesday, June 30, 2015 12:47 PM
• Marked as answer by Wednesday, July 8, 2015 1:45 AM
Tuesday, June 30, 2015 11:09 AM

### All replies

• If the bits are loaded into an array of bytes (for example, using File.ReadAllBytes), then consider the next experimental solution:

byte[] bytes = { 0x1C, 0xE5, /* ... */ };

byte m = 1 << 7;

int i = 0;

Func<int, uint> getNext = ( n ) =>

{

uint r = 0;

while( --n >= 0 )

{

r = ( r << 1 ) | ( ( bytes[i] & m ) == 0 ? 0u : 1u );

if( ( m >>= 1 ) == 0 )

{

m = 1 << 7;

++i;

}

}

return r;

};

uint TPR = getNext( 1 );

uint GK = getNext( 3 );

uint VGR = getNext( 5 );

uint VZ = getNext( 5 );

• Proposed as answer by Tuesday, June 30, 2015 12:47 PM
• Marked as answer by Wednesday, July 8, 2015 1:45 AM
Tuesday, June 30, 2015 11:09 AM
• Hi Viorel,

It worked great. Thanks a lot..

Warm Regards,

Hari

click "Proposed As Answer by" if this post solves your problem or "Vote As Helpful" if a post has been useful to you Happy Programming! Hari

Wednesday, July 8, 2015 12:05 PM