649 views
2 votes
2 votes
Which of the following operators can be used if a portion of a given bit patterns needs to be copied to a new word,while the remainder of the new word is filled with 0s?

1. Bitwise AND

2. Bitwise OR

3. Bitwise XOR

4. Bitwise AND

2 Answers

Best answer
3 votes
3 votes

Answer : Bitwise AND

Here is some explanation :

#include <stdio.h>
#define N 4 		// how many bits we need to check

void display_bits(unsigned int data) {
	for(int i = (sizeof(int) << 3) -1;i>=0;i--) {
		(data&(1<<i))?printf("1"):printf("0");
	}
}
int main() {
	
	printf("1st Example : \n");
    // last 4 bits we need
	unsigned int mask = 0;
	//prepare the mask
	mask |= (1<<0) | (1<<1) | (1<<2) |(1<<3); // or mask |= 15;

	unsigned int data1 = 205;
	printf("Here is the data bits : \n");
	display_bits(data1);
	printf("\n");

	unsigned int result1 = data1 & mask;

	printf("Here is the result bits after masking\n");
	display_bits(result1);
	printf("\n");

	printf("-----------------------------------------\n");
	printf("2nd Example : \n");
	// Another example
	mask = 0;

	int pos[N] = {2,3,6,7}; // positions where we need to check the data bits
							// other positions we dont care 	
	// prepare the mask
	for(int i = 0; i<N ; i++) {
		mask = mask | (1<<pos[i]);	
	}
	// mask is ready
	

	// this is our data
	unsigned int data2 = 345;
	printf("Here is the data bits : \n");
	display_bits(data2);
	printf("\n");

	printf("Here is the result bits after masking\n");
	// result is the new word they are taking about
	unsigned int result2 = data2 & mask;
	display_bits(result2);
	printf("\n");

	return 0;
}

Output:

1st Example : 
Here is the data bits : 
00000000000000000000000011001101
Here is the result bits after masking
00000000000000000000000000001101
-----------------------------------------
2nd Example : 
Here is the data bits : 
00000000000000000000000101011001
Here is the result bits after masking
00000000000000000000000001001000
selected by
0 votes
0 votes
I think it should be bit wise or because it won't create any new data only those position in old word which has bit set would be reset to 1 rest will remain 0

E.g.

010101010010 is bit word and we have to copy first 4 bits then

0101 $\vee$  00000000 = 00000101.

Related questions

0 votes
0 votes
1 answer
1
VS asked Apr 9, 2017
379 views
0 votes
0 votes
2 answers
2
VS asked Apr 9, 2017
298 views
0 votes
0 votes
2 answers
3
VS asked Apr 9, 2017
450 views
0 votes
0 votes
3 answers
4
VS asked Apr 9, 2017
461 views