Hi I am trying to to write a hexadecimal command into serial port, where i need to convert a hex string into particular byte array format in C, having problem with parsing escape character. please help to implement this below function. Thanks.
int hex2byte(char* write_buf)
{
//code to parse this string into byte array removing escape character and keeping other special character as it is
// resize str, In this case it resize strlen(str)=14 bytes into 5 bytes array;
// Goal is to Fill the str in this desired way
// write_buf = {0x02, 0x00, ';' ,';', 0x03};
// Or
// write_buf = {0x02, 0x00, 0x3b ,0x3b, 0x03};
return size_of_write_buf;
}
Run ./serial -w "\x02\x00;;\x03"
OUTPUT: write_buf=\x02\x00;;\x03 size=14 0x5c,0x78,0x30,0x32,0x5c,0x78,0x30,0x30,0x3b,0x3b,0x5c,0x78,0x30,0x33
Here The issue I am getting for option -w write_buf = "\x02\x00;;\x03" getting total 14 bytes, but I need this data to be in 5 bytes e.g 0x02, 0x00, 0x3b ,0x3b, 0x03.
//serial.c
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <getopt.h>
int main(int argc, char **argv)
{
int opt;
char *write_buf= NULL;
int i;
while ((opt = getopt(argc, argv, "w:")) != -1)
{
switch (opt) {
case 'w':
write_buf = optarg;
printf("write_buf=%s size=%ld \n", write_buf, strlen(write_buf));
for(i=0; i<14; i++)
printf("0x%02x\n", write_buf[i]);
/****Implement This function*****/
/* int size= hex2byte(write_buf);
for (int i=0; i<size;i++)
printf("0x%02x\n",write_buf[i]);
Should print 0x02, 0x00, 0x3b ,0x3b, 0x03.
*/
break;
}
}
return 0;
}
char*
but the returned value is saved in an int... – 4386427 Nov 15 at 10:24'\\'
. Is the next character an'x'
. If so parse the following pair of characters as a hex value. – user3121023 Nov 16 at 12:28