CareerCup Interview Question
Developer Program EngineersCountry: India
This should do.
boolean getBit(int num, int i)
{
if ((num&(1<<(i-1)))!=0) return 1 ;
else 0 ;
}
If the number is 10, for the pos 2, we will get 1 as bit as per abv logic. Which is a wrong answer
/*
* In general, a 32 bit register has the following bits: {31, 30,...,i,..., 1, 0}.
* where i is zero based.
*
* If passing -O3 or -Os to ARM gcc,
* both solutions will generate the same ARM asm code.
* r0: num
* r1: i
* lsr.w r0, r0, r1
* and.w r0,r0,#1
* bx lr
*/
uint32_t getBit(uint32_t regValue, int i)
{
return (regValue >> i) & 1;
}
It all depends on whether you count the bits from the left or from the right and whether you start counting with 0 or 1.
- eugene.yarovoi February 20, 2012