2.81 Generate Bits
★★
Problem:
Write C expressions to generate the bit patterns that follow, where a^k represents k repetitions of symbol a. Assume a w-bit data type. Your code may contain references to parameters j
and k
, representing the values of j and k, but not a parameter representing w.
A. 1^{w-k}0{k}
-1 << k
B. 0^{w-k-j} 1^k 0^j
~(-1 << k) << j
Code:
#include <stdio.h>
#include <assert.h>
/* 0 <= k < w */
int A(int k) {
return -1 << k;
}
/* 0 <= k,j < w */
int B(int k, int j) {
return ~(-1 << k) <<j;
}
int main() {
assert(A(3) == 0xFFFFFFF8);
assert(B(3, 4) == 0x00000070);
return 0;
}
Last updated
Was this helpful?