gpt4 book ai didi

c - 如何将十六进制字符串发送到串口?

转载 作者:太空宇宙 更新时间:2023-11-04 10:03:51 30 4
gpt4 key购买 nike

我正在开发一个串行通信程序,用于在主机 (Linux) 和微 Controller 之间发送和接收数据。现在我必须将十六进制字节的数据发送到 MCU。那么如何在不使用 sprint/printf 的情况下将我的缓冲区字符串数据转换为十六进制字符串,以便用户向 MCU 发送类似“AA12CDFF1000001201”而不是“\xAA\x12\xCD\xFF\x10\x00\x00\x12\x01”的字符串。我也看到了 Sending Hexadecimal to Serial Port但它没有帮助,因为它说我可以使用 sprintf 将字符串转换为十六进制,但在我的例子中,我不想使用 sprinf。基本上我想要的是:如果用户输入 = "AA12CDFF1000001201"我必须将其转换为以下格式 "\xAA\x12\xCD\xFF\x10\x00\x00\x12\x01"然后将其写入串口。

#include <stdio.h>   /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
void main()
{
int fd;
fd = open("/dev/ttyf1", O_RDWR | O_NOCTTY | O_NDELAY);
char buff[]="\xAA\x12\xCD\xFF\x10\x00\x00\x12\x01";
write(fd, buff, sizeof(buff));
close(fd);
}

最佳答案

经过与 Hessam 和 Arkku 的富有成果的讨论,新版本的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* str2hexstr(char* inbuff) {

char *outbuff;

if (strlen(inbuff)%2) {
outbuff=malloc((strlen(inbuff)*2+3)*sizeof(char));
outbuff[strlen(inbuff)*2+2]='\0'; }
else {
outbuff=malloc(strlen(inbuff)*2+1*sizeof(char));
outbuff[strlen(inbuff)*2]='\0'; }

for (int strin=0,strout=0;strin<strlen(inbuff);) {
outbuff[strout++]='\\';
outbuff[strout++]='x';
outbuff[strout++]=(!strin&&strlen(inbuff)%2)?'0':inbuff[strin++];
outbuff[strout++]=inbuff[strin++];
}
return(outbuff);
}
int main()
{
char inbuff1[]="123",inbuff2[]="1234";
char *outbuff;

outbuff=str2hexstr(inbuff1);
printf("%s\n",outbuff);
free(outbuff);
outbuff=str2hexstr(inbuff2);
printf("%s\n",outbuff);
free(outbuff);
return 0;
}

关于c - 如何将十六进制字符串发送到串口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54050523/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com