将char *转换为uint8_t [英] Convert char* to uint8_t

查看:5837
本文介绍了将char *转换为uint8_t的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要通过CAN协议传输消息

I transfer message trough a CAN protocol.

为此, 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].

我的问题是,即使我在编译期间没有错误, strong> 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 a number? E.g. char* bufferSlidePressure = "123";?

如果是这样,我只需:

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆