通过struct检查缓冲区

时间:2017-09-23 06:37:26

标签: c struct

我是这个主题的新手,我有unsinged char *buffer

我试图一次检查3个字节

我想也许这可以通过二维数组来解决。

所以我试过了 -

unsigned char *bytes[3] = {};
*bytes = buffer;

但是我看到这是一个创建3个unsigned char *

类型元素的数组的符号

有没有办法实现这一点,而不必memcpy

任何指针都非常感谢。

这种方法似乎有效

typedef struct utf8 {
    unsigned char bytes[3];
};

typedef struct utf8 utf8x;

utf8x *xx = (utf8x *) buffer; //buffer is a return from fread (unsinged char *)

if (xx->bytes[0] == 0xe0) {
   printf("scratch");
}

但是我仍在试图弄清楚如何比较所有字节,我想如果我将xx->字节转换为3字节,它应该可以工作。

1 个答案:

答案 0 :(得分:2)

您想一次比较缓冲区的三个字节。你可以使用memcmp()(一个好的编译器将优化出来,这样就没有实际的函数调用)来做到这一点。例如:

utf8x *xx = (utf8x *) buff;

if (memcmp(&xx->bytes[0], "\100\50\10", 3) == 0) {
   printf("scratch");
}

如果前三个字节为scratch,那将打印\100 \50 \10