使用strstr的奇怪错误

时间:2017-08-07 16:26:04

标签: c substring strstr

我目前正在STM32F0上为智能电表实施SML阅读器。 一切正常,但我使用strstr

中的string.h时出现问题

现状:

我有一个char数组数据,其中包含通过USART传入的所有数据。它包含Hexnumbers和有效的Textstring。

这个String中的某个地方有这个序列: {0x01,0x01,0x62,0x1b,0x52,0x00,0x55}

我想使用strstr在数据字符串中找到此子字符串的位置。

它适用于此示例字符串,它始终位于数据字符串的最开头:{0x1b,0x1b,0x1b,0x1b,0x01,0x01,0x01,0x01,0x76,0x05}

但如果我使用其他子字符串,它就无法工作。

这是我的代码:

const char needle[] = {0x01,0x01,0x62,0x1b,0x52,0x00,0x55};
    if((needle_ptr = strstr(Data,needle)) == NULL){
        //No Active Power String detected
        flags &= ~NewPowervalue;    //Reset NewPowervalue flag
    }else{

        Powervalue = (needle_ptr[14]<<24) + (needle_ptr[15]<<16) + (needle_ptr[16]<<8) + (needle_ptr[17])/10000;
        //Extract and calculate Powervalue
        flags |= NewPowervalue;     //Set NewPowervalue flag
        Poweroutlets(&Powervalue);
        GPIOC->ODR ^= BLED;
    }

有谁知道我做错了什么?

1 个答案:

答案 0 :(得分:3)

当然它不起作用,因为0x00是asciiz终结符,而strstr()比较asciiz终止的字符串,所以它在0x00处停止比较。

您展示的另一个示例字符串有效,因为它不包含任何0x00。

所以,它归结为你不想比较字符串(因为字符串在C中定义),而是内存区域。

所以,你要么必须使用memmem()函数,如果你的运行时库有它,要么自己编写,这应该不难。 (甚至找到memmem()的某些实现的源代码也不难。)