Reputation: 41
I am currently implementing a SML Reader for Smart Meters on a STM32F0
.
Everything works fine, but I have problems using strstr
from string.h
Current Situation:
I have a char Array Data, which contains all Data coming in over USART. It contains Hexnumbers and a valid Textstring.
Somewhere in this String there is this Sequence:
{0x01,0x01,0x62,0x1b,0x52,0x00,0x55}
.
I want to find the position of this substring in the Datastring using strstr
.
It works just fine with this example string, that is always at the very beginning of the Datastring: {0x1b,0x1b,0x1b,0x1b,0x01,0x01,0x01,0x01,0x76,0x05}
But if I use the other substring it doesn't work.
Here is my Code:
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;
}
Has anyone a clue what I am doing wrong?
Upvotes: 2
Views: 911
Reputation: 61969
Of course it does not work, because 0x00 is the asciiz terminator, and strstr()
compares asciiz-terminated strings, so it stops comparing at 0x00.
The other example string you showed works because it does not contain any 0x00s.
So, what it boils down to is that you do not want to compare strings, (as strings are defined in C,) but areas of memory.
So, you will either have to use the memmem()
function, if your runtime library has it, or write your own, it should not be difficult. (It should not be difficult to even find the source code of some implementation of memmem()
.)
Upvotes: 3