Answered step by step
Verified Expert Solution
Question
1 Approved Answer
A common and very useful application of bitwise operators is in the creating and manipulation of bit fields and bit masks. A bit field is
A common and very useful application of bitwise operators is in the creating and manipulation of bit fields and bit masks. A bit field is a binary word where each bit represents the state of some property in the code, and a bit mask is a bit field that is used to perform parallel operations on multiple bits within another bit field. For example, recall the "Nintendo controller pad" lab in ENME351, where there were 4 buttons defining up, down, left, and right movement. Instead of creating separate variables to record the state of each button, using a bit field provides a much cleaner approach. Consider the following Python variable declarations: b_status = int('1010', 2) # button states (start with right & down on) b_up = int('0001', 2) b_down = int('0010', 2) b_left = int('0100', 2) b_right = int('1000', 2) Here b_status will hold all button states in a single 4-bit field, while the remaining variables define which bit in the field will hold each button state. Based on our discussion about bit fields in class, write Python code with the above global variables, and add the functions given below. For each functions, use the button variables (b_status, b_up, b_down, bjeft, b_right) and one or more logical operators in a single line of code. Note that you may need to add a return() statement, and that for some functions you will also need to either use global to access the button status variable, or pass the status as an argument to your function. setOn(b): # Set a given button state to ON. setOff(b): # Set a given button state to OFF. flip(b): # Flip the state of a button state (0 rightarrow 1 or 1 rightarrow 0), regardless of its initial state. invert(): # Invert all of the bit field properties from their current states. testOn(b): # Test if a given button is ON or OFF using a single assignment # (no //statements) that will return 1 if the button is ON, and 0 if it is OFF. Test your code with a few initial bit states to make sure that every function works, and submit your final code as p2.py
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started