Bit operations is very popular questions in any firmware interview, you might be asked about it many times in a interview (by different interviewers), and those questions are very similar!!!
Bitwise Operators& bitwise AND | bitwise inclusive OR ^ bitwise exclusive OR << left shift >> right shift ~ one's complement (unary)
Swap a and b arounda ^= b; b ^= a; a ^= b; or equivalently, a ^= b ^= a ^= b; note: a^b obtains a mask which has 0 on bits that a and b are the same, and has 1 on bits that a and b are oppsite
Return a mask that set the first 1c & (~c + 1) or c & -c
Return a mask that set the first 0~c & (c + 1) Count number of 1int count_one1(int c){ int i; for (i = 0; c; i++) c ^= (c & -c); return i; }
int count_one2(int c) { int i; for (i = 0; c; i++) c &= (c - 1); return i; }
int count_one3(int c) { int n = 0, i; for (i = 0; i < 32; i++) { if (c & 1) n++; c >>= 1; } return n; } Left rotate a byte by certain bitschar rotate(char c, int i) { i %= 8; return (c << i) | ((unsigned char)c >> (8 - i)); }
Bit operations is very popular questions in any firmware interview, you might be asked about it many times in a interview (by different interviewers), and those questions are very similar!!!
Bitwise Operators
& bitwise AND
| bitwise inclusive OR
^ bitwise exclusive OR
<< left shift
>> right shift
~ one's complement (unary)
Swap a and b around
a ^= b; b ^= a; a ^= b;
or equivalently,
a ^= b ^= a ^= b;
note: a^b obtains a mask which has 0 on bits that a and b are the same, and has 1 on bits that a and b are oppsite
Return a mask that set the first 1
c & (~c + 1) or c & -c
Return a mask that set the first 0
~c & (c + 1)
Count number of 1
int count_one1(int c)
{
int i;
for (i = 0; c; i++)
c ^= (c & -c);
return i;
}
int count_one2(int c)
{
int i;
for (i = 0; c; i++)
c &= (c - 1);
return i;
}
int count_one3(int c)
{
int n = 0, i;
for (i = 0; i < 32; i++) {
if (c & 1)
n++;
c >>= 1;
}
return n;
}
Left rotate a byte by certain bits
char rotate(char c, int i)
{
i %= 8;
return (c << i) | ((unsigned char)c >> (8 - i));
}
thanks
回覆刪除