In: Computer Science
Suppose the cable company represents the channels your TV has access to with a 32-bit integer. Each channel from 0 to 31is represented by one bit, where 1 means the channel is enabled and 0 means the channel is disabled. Assume channel 0 is the least significant bit. When you get your cable box, the technician sets the 32-bit code.
// for example, this code enables channels 0, 1, and 2 only intcode= 7;
In cableCompany.c, write code for the following tasks. You may not call any “magic” library functions and you may not use any loops. Rather you should just use basic operations like creating and assigning variables, equality (==), ifstatements, and the bitwise operations (~, &, <<, >>, |, ^)
.a.A function that returns whether a particular channel (integer 0-31) is enabled. boolisEnabled(intA, charchannel) { ... }
b.A function that returns a new integer, with the given channel enabled.intenableChannel(intA, charchannel) { ... }
Following is the code with both methods, plus a driver function to understand things :
#include <stdio.h>
#include <stdbool.h>
bool isEnabled(int A, char channel)
{
/*
* To check if a bit/channel is set in A, we use
* bitwise-ANDing with a suitable mask, and then check
* whether the value is equal to 0.
*
* We proceed step by step.
*/
/*
* 1. Create a mask, with
*
* * 1 at position, for the channel to be checked.
* * 0 at all other positions.
*/
unsigned int mask = 1U << channel;
/*
* 2. Do a bitwise-AND with A.
* If the value is equal to 0, it means bit/channel is not set.
*/
if( (A & mask) == 0)
{
return false;
}
/*
* The value is not 0, thus the bit/channel is set.
*/
return true;
}
int enableChannel(int A, char channel)
{
/*
* To set a bit/channel is set in A, we use
* bitwise-ORing with a suitable mask.
*
* We proceed step by step.
*/
/*
* 1. Create a mask, with
*
* * 1 at position, for the channel to be enabled.
* * 0 at all other positions.
*/
unsigned int mask = 1U << channel;
/*
* 2. Do a bitwise-OR with A, and return the result.
*/
return (A | mask);
}
/*
* Driver to test ..
*/
int main()
{
int A = 0;
printf("\n\nIs channel 9 set : %d\n", isEnabled(A, 9));
printf("Is channel 22 set : %d\n", isEnabled(A, 22));
printf("Is channel 31 set : %d\n", isEnabled(A, 31));
printf("\n\nSetting channel 31.\n\n");
A = enableChannel(A, 31);
printf("Is channel 9 set : %d\n", isEnabled(A, 9));
printf("Is channel 22 set : %d\n", isEnabled(A, 22));
printf("Is channel 31 set : %d\n", isEnabled(A, 31));
printf("\n\nSetting channel 22.\n\n");
A = enableChannel(A, 22);
printf("Is channel 9 set : %d\n", isEnabled(A, 9));
printf("Is channel 22 set : %d\n", isEnabled(A, 22));
printf("Is channel 31 set : %d\n", isEnabled(A, 31));
printf("\n\n");
return 0;
}
Following is the output :
Is channel 9 set : 0
Is channel 22 set : 0
Is channel 31 set : 0
Setting channel 31.
Is channel 9 set : 0
Is channel 22 set : 0
Is channel 31 set : 1
Setting channel 22.
Is channel 9 set : 0
Is channel 22 set : 1
Is channel 31 set : 1