Pergunta de entrevista da empresa Qualcomm

Write a C program to encode bits in a 32-bit number such that, most significant 16 bits should be reversed but lower 16 bits should be untouched. Then asked to generalize this to any number of bits.

Respostas da entrevista

Sigiloso

15 de jun. de 2017

The idea is to reverse the entire 32-bits first and then left shift the resulting number by 16 bits so that the upper 16 bits are now reversed. In the second phase, with the help of a mask zero out the most significant 16 bits. Now XOR the two number to get the desired encoded number.

1

Sigiloso

23 de set. de 2019

To solve this problem, below properties of XOR can be used: 1 ^ x => ~x 0 ^ x => x Step 1: Create a mask with upper 16 bits are set and lower 16 bits are cleared. Step 2: XOR input and mask. Int invertUpper16 (int x) { int mask = ~((1 0000_0000_0000_0001_0000_0000_0000_0000 When we subtract 1 from 1 0000_0000_0000_0000_1111_1111_1111_1111 When we negate (1 1111_1111_1111_1111_0000_0000_0000_0000; Generalized solution: Int invertUpper16 (int x) ; int size = 16; Int mask = ~((1 << (size+1))-1); x ^= mask; Return x; }

Sigiloso

23 de set. de 2019

For some reason, above explanation is got trimmed in the middle (@ int mask = onwards). But anyway, generalized final solution is displayed correct.