Hello. How to get the value of a specific bit in a byte? Suppose we have a byte with bits of the form: 00110101

How can I get a value of 4 or 5 bits? An example can be shown in any language, preferably C or Delphi.

  • one
    In C, if (b & (1 << 4)) { // бит №4 (у первого бита номер 0) установлен ... - avp
  • Could you describe in more detail what this design means? As I understand it, b is what we have byte for. And 1 << 4 is this how we shift by 4 bits? - user241285
  • For sure. b is your byte, and (1 << 4) bitmask (4th bit is set, the remaining 0 ( << this is bitwise left shift operation)) and & this is bitwise AND operation - avp
  • In general, your construction can be explained as follows: Take a byte and do something with its bits, then take byte 4 and set its value to 1 - user241285
  • one

2 answers 2

If you are interested in the literal value of a bit (ie, 0 or 1 ), then in C, the value of the i -th bit of the number n can be obtained as

 (n >> i) & 1u 

If you are interested in the weighted value of a bit (ie, 0 or 8 for bit number 3), then in C, the value of the i -th bit of the number n can be obtained as

 n & (1u << i) 

(This implies numbering from zero from low bits to high bits.)

    A function on Delphi to check if a particular bit is set to a 32-bit number:

     function IsBitSet(const AValue: Cardinal; const ABit: Byte): Boolean; begin Result := (AValue and (1 shl ABit)) <> 0; end; 

    The operation (1 shl ABit) (a random shift of the value of an integer to the left, by a specified number of bits) generates a number in which only one bit is set to exactly that position that interests us. This number is called a mask .

    Further, a logical AND operation is applied to the input value and mask, which results in another number that is either 0 (all bits are set to 0) or equal to the mask, i.e. Only one bit is set. Accordingly, by comparing the result with zero, it can be concluded that the required bit is set or not.

    Picture explaining the operation of the logical AND operation:

    AND

    The resulting bit is considered set only if the corresponding bit is also set for both operands.

    In your example, when searching for the 4th bit, this addition will be performed:

     00110101 - входное значение 00001000 - маска -------- 00000000 - результат = 0, т.е 4-й бит не установлен