1. 程式人生 > >實時求一段0、1序列1的比例

實時求一段0、1序列1的比例

#define  MIN(a,b) ((a) < (b) ? (a) : (b))
#define FLAG_BUFF_LEN_BYTE 125
#define FLAG_BUFF_LEN_BIT ( FLAG_BUFF_LEN_BYTE * 8)
#define LONG_SMOOTH_NUM 1000

unsigned short short_count; ///< Number of  shorts
unsigned char buff[FLAG_BUFF_LEN_BYTE]; ///< The flag buff, save as bit
int pre_count;
int index_byte; ///< The index by byte
unsigned int index_bit; ///< The index by bit float ratio_short_mean; ///< The short ratio float ratio_long_smooth; ///< The long ratio short_count = 0; memset(buff, 0, sizeof(buff)); pre_count = 0; index_byte = 0; index_bit = 1; ratio_short_mean = 0; ratio_long_smooth = 0; if (flag) { count += (1
- ((buff[index_byte] & (unsigned char)index_bit) != 0 ? 1 : 0)); // if bit is 0, plus 1;else do nothing buff[index_byte] |= index_bit; // flush new value } else { count -= (1 - ((buff[index_byte] & (unsigned char)index_bit) == 0 ? 1 : 0)); // if bit is 1, minus 1;else do nothing buff[index_byte] &= (~index_bit); // flush new value
} index_bit <<= 1; if (index_bit > 128) { index_bit = 1; index_byte = (index_byte + 1) % FLAG_BUFF_LEN_BYTE; } if (pre_count < 1073741824) { pre_count++; } ratio_short_mean = (float)short_count / MIN(pre_count, FLAG_BUFF_LEN_BIT); ratio_long_smooth = ((pre_count - 1) * ratio_long_smooth + flag) / MIN(pre_count, LONG_SMOOTH_NUM);