bitget working with an example
21 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Can anyone explain bitget function with an example
I've looked it in the documentation but its kinda confusing for me to understand
0 commentaires
Réponse acceptée
Scott MacKenzie
le 4 Mai 2021
Modifié(e) : Scott MacKenzie
le 4 Mai 2021
Wow, I just looked and you're right about the documentation.
The basic operation of bitget is to extract a bit from the binary representation of an integer. Position "1" is the bit on the right, or least-significant bit. So, if integer x is 25, that's
000000011001
in binary. Count from the right. So,
bitget(x,1) = 1
bitget(x,2) = 0
bitget(x,3) = 0
bitget(x,4) = 1
bitget(x,5) = 0
bitget(x,6) = 0
and so on.
Got it?
2 commentaires
Plus de réponses (1)
Turlough Hughes
le 4 Mai 2021
Modifié(e) : Turlough Hughes
le 4 Mai 2021
As I'm sure you know, computers communicate at the lowest level with underlying switch-like states known as bits, whose digital representations in MATLAB are typically logical 1/0 or true/false. The different classes of numeric data use different amounts of bits. Take 8-bit unsigned integers (uint8), which were also used in the examples in bitget's documentation; the 8 bits allow for 256 (or ) possible integer values, and in the case of uint8, the values range from 0 to 255. The bit vector 00000001 represents uint8 value 1. Subsequent examples for the uint8 class are
2: 00000010
3: 00000011
4: 00000100
5: 00000101
all the way up to
255: 11111111
Consider the following where a1 is the unsigned 8-bit integer value 1 and we want the states of all 8 bits associated with the value. The second input is 8:-1:1, so we can get the logical values at positions 8,7,6,5,4,3,2,1:
a1 = uint8(1)
bitget(a1,8:-1:1)
Note, 8:-1:1 is used because the bitget function conventionally reads right-to-left. Similarly, we can get the bits for uint8 values 2 and 3
a2 = uint8(2);
bitget(a2,8:-1:1)
a3 = uint8(3);
b = bitget(a3,8:-1:1)
If instead of inputting positions 8:-1:1 we seek the bits at position 1 (on the right) we get the following:
b = bitget(a1,1)
b = bitget(a2,1)
b = bitget(a3,1)
I hope this clarifies how the bitget function works. A point of confusion may also arise when the first input is an array with 2 or more elements because bitget only allows us to specify ONE bit position for each value in the input arrays. We can achieve the same result as the previous three lines of code, however this time, for illustration, we return the bits in position two for each of the uint8 values:
b = bitget([a1 a2 a3],[2 2 2])
0 commentaires
Voir également
Catégories
En savoir plus sur Whos dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!