I am trying to calculate a value in function of bits in a word of variable length. Starting MSB, if bit is 1 then the value is 1/2^i. This value is multiplied by a scaling factor
Example: 110010 this would be (1/2 + 1/4 + 1/64) * scaling_factor
I have programmed it with a for loop; any idea of how this could be done avoiding the loop?
This is the code:
double dec_bnr (unsigned long data, int significant_bits, double scaling_factor)
{
unsigned int temp;
unsigned int bnr_locmask = 0x8000000;
temp = data & bnr_locmasks[significant_bits-1];
double result = 0;
for (int i=0; i<significant_bits; i++){
if((temp & bnr_locmask)==bnr_locmask){
result+=pow (0.5, i+1);
}
bnr_locmask = bnr_locmask >> 1;
}
return result * scaling_factor;
}
Thank you in advance!
Edit: Thank you for your answers; however, what I am trying to say is not what you propose. Please, let me add an example: data=a0280
A 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192
1/A 0,5 0,125 0,000488281 0,00012207
data 1 0 1 0 0 0 0 0 0 0 1 0 1 0000000
result = scaling_factor*Sum(data/A)
We only take into account the value 1/A if the bit for that position is 1.
bnr_locmasks?ldexp((double)data, -20)floats the integer 0xA0280 and then divides by (2^20)... it's not clear to me what the various respondents are missing :-(