bitget working with an example

19 次查看(过去 30 天)
Can anyone explain bitget function with an example
I've looked it in the documentation but its kinda confusing for me to understand

采纳的回答

Scott MacKenzie
Scott MacKenzie 2021-5-4
编辑:Scott MacKenzie 2021-5-4
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?

更多回答(1 个)

Turlough Hughes
Turlough Hughes 2021-5-4
编辑:Turlough Hughes 2021-5-4
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)
a1 = uint8 1
bitget(a1,8:-1:1)
ans = 1×8
0 0 0 0 0 0 0 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)
ans = 1×8
0 0 0 0 0 0 1 0
a3 = uint8(3);
b = bitget(a3,8:-1:1)
b = 1×8
0 0 0 0 0 0 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 = uint8 1
b = bitget(a2,1)
b = uint8 0
b = bitget(a3,1)
b = uint8 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])
b = 1×3
0 1 1

类别

Help CenterFile Exchange 中查找有关 Whos 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by