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.
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.
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:
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-й бит не установлен Source: https://ru.stackoverflow.com/questions/642549/
All Articles
if (b & (1 << 4)) { // бит №4 (у первого бита номер 0) установлен ...- avp<<this is bitwise left shift operation)) and&this is bitwiseANDoperation - avp