Python 2.7.9 ,Ubuntu 15.04
I am using the assignment “tmp=(dta>>i&1)” to iterate the value of dta (an int)
to test a bit position (i) to select binary value (1 or 0) for that bit position. The values(s)
are appended to a list but are stored in a reverse sequence.
I have a tried other variations of the assignment but this one seems to be the only way to go.
QUESTION: In trying to understand that syntax, does that mean that the value
of dta is actually shifted left and then the bit position (i) is anded (&) with that value?
Some years past I had to do something like this using a for loop in C and the shift operator
to get the 1 or 0 value. But, I was using a left shift to build up a string and did not have
to reverse the string or array.
I realize that I can use Python built-in “bin(x)” to do the same thing . But I want to understand if there is
a method to cycle through the data value and from the LSB to the MSB (left shift). Is this an issue with big endian/little endian? If my memory serves me, I also did not shift the data tested but instead was shifting the bit to and with the
data. I can not find the original code (C) as that was some time ago. It is not the end of the world, I just thought
I would be able to do this with no major head banging. I guess I am suffering from RAMnesia ![]()
The above mentioned assignment syntax was from stackoverflow . And as I mentioned it works , I just want to
know why it is the data being shifted instead of the bit (i) ?
The below snippet is the for loop used to extract the 1 or 0 values to a list. If the complete listing is required
I can post that as well.
Code:
for i in range(0,size):
tmp=(dta>>i&1) #don't have to convert to int, only 0 or 1, True or False
l.append(tmp) #add value to list
#================================= end FOR loop ==============================
- - , .
برچسب:
نویسنده: استخدام کار