Serial Serial character type const char *, and unsigned char * problem

Disclaimer: This article is a blogger original article, without the bloggers allowed to reprint, please set the link to the article! https://blog.csdn.net/qq_30460905/article/details/90720518

When the debt owed to learn C, sooner or later have to repay. . . Forget the basics

char character type (-128-127), over 127 will overflow, unsigned char unsigned character type (0-255), both of which are one byte.

When a char value is positive, the converted value of the original value.
When the char type is negative, the sign bit value will be converted into the original data bits, i.e., the result is an unsigned code representative of the original values of complement.

The calculation formula is, the result value 256 = + original value.

Reference Links: https://zhidao.baidu.com/question/487910754.html

1, the problem description

After use the serial read data, data conversion needs to be read, and starts data types do not pay attention, found int (char) is negative, the following print hex

data[0]: 0x55
data[1]: 0xffffffaa
data[2]: 0x3
data[3]: 0xffffff84
data[4]: 0x1
data[5]: 0x2
data[6]: 0x1

As part of the program

#include "serial/serial.h"
string rec_buffer;  //串口数据接收变量

string port("/dev/ttyUSB0");//串口号
unsigned long baud = 115200;//小车串口波特率
serial::Serial my_serial(port, baud, serial::Timeout::simpleTimeout(1000));//配置串口
rec_buffer =my_serial.read(my_serial.available());    //获取串口发送来的数据
const char *receive_data=rec_buffer.data(); //保存串口发送来的数据

Add cast, will receve_data, converted to unsigned pointer b:

Reference Links: https://blog.csdn.net/igaming/article/details/25978235

unsigned char *b;
b = (unsigned char *)receive_data;

Connecting the two bytes of data, plus eight upper left data position data, note parentheses, plus higher priority than the sign in displacement:

int distance;
cout<<"b4: "<<int(b[4])<<" b5: "<<int(b[5])<<endl;
distance= (b[4]<<8)+b[5];
cout<<"distance: "<<distance<<endl;

 

Guess you like

Origin blog.csdn.net/qq_30460905/article/details/90720518