Read a single bit from a buffer of char

时间:2016-02-12 22:08:42

标签: c arrays bitmask

I would to implement a function like this:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div ng-app="roleApp" ng-controller="myCtrl">
  <h1>ROLES:</h1>
  <div ng-repeat="personPerRole in rolesToFilter() | filter:filterRoles">
    <h2>{{personPerRole.role}} :</h2>
    <p ng-repeat="person in people | filter:{role: personPerRole.role}">{{person.name}}</p>
  </div>
</div>

where index is the offset of the bit that I would want to read.

How do I use bit shifting or masking to achieve this?

3 个答案:

答案 0 :(得分:4)

You might want to split this into three separate tasks:

  1. Determining which Err.Clear contains the bit that you're looking for.
  2. Determining the bit offset into that char that you need to read.
  3. Actually selecting that bit out of that char.

I'll leave parts (1) and (2) as exercises, since they're not too bad. For part (3), one trick you might find useful would be to do a bitwise AND between the byte in question and a byte with a single char bit at the index that you want. For example, suppose you want to get the fourth bit out of a byte. You could then do something like this:

1

So think about the following: how would you generate the mask that you need given that you know the bit index? And how would you convert the AND result back to a single bit?

Good luck!

答案 1 :(得分:1)

IF (INSTR(p_msg, 'Error One') = 'Error One') ....

should do it (that is, view buffer[index/8] & (1u<<(index%8)) as a bit array and test the bit at buffer).

Similarly:

index

should set the buffer[index/8] |= (1u<<(index%8)) bit.

Or you could store a table of the eight shift states of 1 and index-th against that

&

If your compiler doesn't optimize those unsigned char bits[] = { 1u<<0, 1u<<1, 1u<<2, 1u<<3, 1u<<4, 1u<<5, 1u<<6, 1u<<7 }; and / to bit ops (more efficient), then:

%

so

 unsigned_int / 8  == unsigned_int >> 3
 unsigned_int % 8  == unsigned_int & 0x07  //0x07 == 0000 0111

答案 2 :(得分:0)

您的函数的一种可能实现可能如下所示:

int read_single_bit(unsigned char* buffer, unsigned int index)
{
    unsigned char c = buffer[index / 8]; //getting the byte which contains the bit
    unsigned int bit_position = index % 8; //getting the position of that bit within the byte

    return ((c >> (7 - bit_position)) & 1);
    //shifting that byte to the right with (7 - bit_position) will move the bit whose value you want to know at "the end" of the byte.
    //then, by doing bitwise AND with the new byte and 1 (whose binary representation is 00000001) will yield 1 or 0, depending on the value of the bit you need.
}