I am writing the main function in C language.
The information you sent me has been separated, but I would like to write if the first letter starts with 7E.However, please let me know if it doesn't work.
The unsigned char buff should start with 7E, so
if(strcmp(buff, "7E", 2)==0){
I thought so, but I can't use strcmp with unsigned char, so I don't know.I recently started studying C language, so there are many things I don't understand.
I'm sorry, but I appreciate your cooperation.
static void tty-read (void)
{
inti = 0;
unsigned char buff [1024];
size-tlen;
TTYnitBlock (0x7E, 1, 2, 0, 1);
for (;;)
len = TTYReadFrame (ttyfd, buff, 1024);
if(len<0){
fprintf(stderr, "TTYReadFrame%zd%d\n", len, errno);
exit(1);
}
printf("Frame: %dlen=%zd|n", i++, len);
dump-packet (buff, len);
}
}
To determine that the leading value is 0x7E:
if(buff[0]==0x7E){
If you literally want to check "7E", you can cast and strcmp.
if(strncmp((char const*)buff, "7E", 2)==0){
We recommend using memcmp
or using a safer self-made function.
#include<stdio.h>
# include<stdbool.h>
# include <stdint.h>
# include <string.h>
# include <assert.h>
/**
* Returns true if bytes starts with target or false if not included
*/
static bool
contains(constructed char*bytes,
uint32_t bytes_size,
constructed char*target,
uint32_t target_size) {
uint32_ti;
for(i=0;i<bytes_size&&i<target_size;++i){
if(bytes[i]!=target[i]){
break;
}
}
return i==target_size;
}
/**
* test
*/
void
test(void){
assert(contains("7E****", 6, "7E", 2));
US>assert(!contains("7F****", 6, "7E",
US>assert(!contains("7F", 2, "7EE",
assert(contains("777", 3, "777", 3));
US>assert(!contains("777", 3, "333",
}
int
main(void){
unsigned char buf [1024] = "7E****";
// the simplest way
if(buf[0]=='7'&buf[1]=='E'){
puts("easy");
}
// method using memcmp
if(memcmp(buf, "7E", 2)==0){
puts("memcmp");
}
// content method
if(contains(buf, size of buf, "7E", 2){
puts("contains");
}
test();
return 0;
}
© 2024 OneMinuteCode. All rights reserved.