I am using C for developing my program and I found out from an example code
unHiByte = unVal >> 8;
What does this mean? If unVal = 250
. What could be the value for unHiByte
?
I am using C for developing my program and I found out from an example code
unHiByte = unVal >> 8;
What does this mean? If unVal = 250
. What could be the value for unHiByte
?
>>
in programming is a bitwise operation. The operation >>
means shift right operation.
So unVal >> 8
means shift right unVal
by 8 bits. Shifting the bits to the right can be interpreted as dividing the value by 2.
Hence, unHiByte = unval >> 8
means unHiByte = unVal/(2^8)
(divide unVal
by 2 eight times)
Without going into the shift operator itself (since that is answered already), here the assumption is that unVal is a two byte variable with a high byte (the upper 8 bits) and a low byte (the lower 8 bits). The intent is to obtain the value produced by ONLY the upper 8 bits and discarding the lower bits.
The shift operator though should easily be learned via any book / tutorial and perhaps was the reason some one down voted the question.
The >>
is a bitwise right shift.
It operates on bits. With unHiByte = unVal >> 8;
When unVal=250
.
Right shift means to shift the bits to the right. So when you shift 1111 1010
, 8 digits to right you get 0000 0000
.
Note: You can easily determine the right shift operation result by dividing the number to the left of >>
by 2^(number to right of >>
)
So, 250/2
8= 0
For example: if you have a hex 0x2A63
and you want to take 2A
or you want to take 63
out of it, then you will do this.
For example, if we convert 2A63
to binary which is: 0010101001100011
. (that is 16 bits, first 8 bits are 2A
and the second 8 bits are 63
)
The issue is that binary always starts from right. So we have to push the first 8 bits (2A
) to the right side to be able to get it.
uint16_t hex = 0x2A63;
uint8_t part2A = (uint8_t)(hex >> 8) // Pushed the first
// eight bits (2A) to right and (63) is gone out of the way. Now we have 0000000000101010
// Now Line 2 returns for us 0x2A which the last 8 bits (2A).
// To get 63 we will do simply:
uint8_t part63 = (uint8_t)hex; // As by default the 63 is on the right most side in the binary.
It is that simple.