C语言 通过for循环逐个检查每个字节,如果连续三个字节是01 02 03则认为有效
时间: 2024-10-16 22:14:18 浏览: 22
在C语言中,如果你想通过`for`循环逐个检查字节序列,并在找到连续三个字节为`01`, `02`, `03`时认为序列有效,你可以这样做:
```c
#include <stdio.h>
#define CHECK_SEQUENCE(arr, length) \
for (size_t i = 0; i < length - 2 && arr[i] == 01 && arr[i + 1] == 02 && arr[i + 2] == 03; i++)
void check_validity(const char* data, size_t len) {
const uint8_t *bytes = (const uint8_t*)data; // 将字节数组转换为便于操作的指针
if (len >= 3) {
CHECK_SEQUENCE(bytes, len);
if (i == len - 2) {
printf("Found a valid sequence of 01, 02, and 03 at indices %zu, %zu, and %zu.\n", i, i+1, i+2);
} else {
printf("No valid sequence found in the given data.\n");
}
} else {
printf("Data is too short to contain a valid sequence.\n");
}
}
int main() {
const char byte_sequence[] = {01, 03, 02, 05, DC, BA, 8D};
check_validity(byte_sequence, sizeof(byte_sequence) / sizeof(byte_sequence[0]));
return 0;
}
```
这个函数会检查给定的字节数组`byte_sequence`,如果连续发现三个字节等于`01`, `02`, 和 `03`,则认为有效。请注意,这个例子假设数据是以字节形式存储的,所以用了`uint8_t`。
阅读全文