首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

C++ 十六进制发送数据的串口通讯有关问题

2012-05-21 
C++ 十六进制发送数据的串口通讯问题现有字符串 str1 07 0A 02 10 03 00 00 00 00 00我如何才可以以十

C++ 十六进制发送数据的串口通讯问题
现有字符串 str1 = "07 0A 02 10 03 00 00 00 00 00"
我如何才可以以十六进制的方式发送给串口,初学者求教!谢谢指点!

[解决办法]

C/C++ code
[User:root Time:14:25:17 Path:/home/liangdong/c]$ ./output 07 0a 02 10 03 00 00 00 00 00 [User:root Time:14:25:18 Path:/home/liangdong/c]$ cat src/main.c #include <stdio.h>#include <stdlib.h>#include <string.h>int char2bits(char ch) {        int bits = 0;        if (ch >= 'a' && ch <= 'z') {                bits = ch - 'a' + 10;        } else if (ch >= 'A' && ch <= 'Z') {                bits = ch - 'A' + 10;        } else if (ch >= '0' && ch <= '9') {                bits = ch - '0';        } else {                bits = -1;        }        return bits;}int hex2bytes(const char *hex, char *bytes, int size) {        int len = strlen(hex);        int nbytes = (len + 1) / 3;        if (nbytes > size) {                return -1;        }         int n;        for (n = 0; n != nbytes; ++ n) {                int lndx = n * 3;                int rndx = lndx + 1;                int lbits = char2bits(hex[lndx]);                int rbits = char2bits(hex[rndx]);                if (lbits == -1 || rbits == -1) {                        return -1;                }                bytes[n] = (lbits << 4) | rbits;        }        return nbytes;}int main(int argc, char* const argv[]) {        const char *hex = "07 0A 02 10 03 00 00 00 00 00";        char stream[10];        int nbytes = hex2bytes(hex, stream, 10);        if (nbytes != -1) {                int i = 0;                for ( ; i < nbytes; ++ i) {                        printf("%02x ", stream[i]);                }        }        return 0;} 

热点排行