34.9k views
5 votes
Implement the function getBits that has the prototype below. The function initializes the bits array with the 0's and 1's associated with the value parameter. For example, calling the function with the value 0xabcd will initialize the array as follows: 1 0 1 0 1 0 1 1 1 1 0 0 1 1 0 1. You can assume that an unsigned short has 2 bytes. For this problem you can use only 1 for loop.

1 Answer

5 votes

Final answer:

The function getBits initializes a 16-element array with the binary representation of an unsigned short value. It iterates in reverse order from the most significant bit to the least significant bit, using bit shifting and a bitwise AND to extract each bit.

Step-by-step explanation:

The function getBits needs to take an unsigned short value and initialize a bits array with the binary representation of the value. Since an unsigned short is 2 bytes, which equals 16 bits, the array will have 16 elements. Here's an example of how this can be implemented using a for loop:

void getBits(unsigned short value, int bits[16]) {
for(int i = 15; i >= 0; i--) {
bits[i] = (value >> (15-i)) & 1;
}
}
This loop runs from 15 to 0, representing the bit positions from the most significant bit to the least significant bit of the value. The expression value >> (15-i) shifts the value to the right by the amount that aligns the current bit at the least significant position. The bitwise AND with 1 extracts that bit and assigns it to the corresponding position in the bits array.
User Brian Leach
by
8.4k points