64,654
社区成员
发帖
与我相关
我的任务
分享
void foo(void *buffer, size_t size)
{
const int masks[] = {0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80};
auto ptr = reinterpret_cast<intptr_t>(buffer);
auto end = static_cast<intptr_t>(ptr + size);
int maxLength = 0, len = 0, count = 0;
while (ptr < end)
{
auto val = *reinterpret_cast<uint8_t *>(ptr);
for (int i = 7; i >= 0; i--)
{
if (val & masks[i])
{
len++;
if (len > maxLength)
{
maxLength = len;
count = 1;
}
else if (len == maxLength)
{
count++;
}
}
else
{
len = 0;
}
}
ptr++;
}
printf("maxLength = %d, count = %d\n", maxLength, count);
}
uint8_t buffer[] = {0b11000111, 0b10001111, 0b00011111, 0b11110011, 0b11111110, 0b01111111, 0b11000000};
// 输出 maxLength = 9, count = 3
foo(buffer, ARRAYSIZE(buffer));
// 你的例子 输出 maxLength = 4, count = 2
foo(buffer, 2);
unsigned int u = 0;
u |= buffer[0];
u |= ((unsigned int)buffer[1] << 8);
int j = 0;
bool on = true;
int count[9] = {0};
for(int i = 0; i < 16; i+)
{
if(u & (1<<i) ) {
if(on)
count[j]++;
else {
on = true;
count[++j]++;
}
}
else{
on = false;
}
}
for(int i = 0; i < j+1; i++)
{
//这里判断统计后的个数
}