Convert char* to uint8_t(将 char* 转换为 uint8_t)
问题描述
我通过 CAN 协议传输消息.
为此,CAN 消息需要 uint8_t 类型的数据.所以我需要将我的 char* 转换为 uint8_t.通过对本网站的研究,我生成了以下代码:
To do so, the CAN message needs data of uint8_t type. So I need to convert my char* to uint8_t. With my research on this site, I produce this code :
char* bufferSlidePressure = ui->canDataModifiableTableWidget->item(6,3)->text().toUtf8().data();//My char*
/* Conversion */
uint8_t slidePressure [8];
sscanf(bufferSlidePressure,"%c",
&slidePressure[0]);
如您所见,我的 char* 必须适合 sliderPressure[0].
As you may see, my char* must fit in sliderPressure[0].
我的问题是即使我在编译过程中没有错误,slidePressure中的数据完全不正确.确实,我用 char* = 0 对其进行了测试,并且我有未知字符......所以我认为问题必须来自转换.
My problem is that even if I have no error during compilation, the data in slidePressure are totally incorrect. Indeed, I test it with a char* = 0 and I 've got unknow characters ... So I think the problem must come from conversion.
我的数据可以是Bool、Uchar、Ushort和float.
感谢您的帮助.
推荐答案
你的字符串是整数吗?例如.char* bufferSlidePressure = "123";?
Is your string an integer? E.g. char* bufferSlidePressure = "123";?
如果是这样,我会这样做:
If so, I would simply do:
uint8_t slidePressure = (uint8_t)atoi(bufferSlidePressure);
或者,如果您需要将其放入数组中:
Or, if you need to put it in an array:
slidePressure[0] = (uint8_t)atoi(bufferSlidePressure);
根据您的评论,如果您的数据可以是任何内容,我想您必须将其复制到新数据类型的缓冲区中.例如.类似:
Following your comment, if your data could be anything, I guess you would have to copy it into the buffer of the new data type. E.g. something like:
/* in case you'd expect a float*/
float slidePressure;
memcpy(&slidePressure, bufferSlidePressure, sizeof(float));
/* in case you'd expect a bool*/
bool isSlidePressure;
memcpy(&isSlidePressure, bufferSlidePressure, sizeof(bool));
/*same thing for uint8_t, etc */
/* in case you'd expect char buffer, just a byte to byte copy */
char * slidePressure = new char[ size ]; // or a stack buffer
memcpy(slidePressure, (const char*)bufferSlidePressure, size ); // no sizeof, since sizeof(char)=1
这篇关于将 char* 转换为 uint8_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 char* 转换为 uint8_t
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
