接收到数据
uint8_t num;
需要转成 string 类型的数据,不是直接转类型。
uint8_t num = 0 -> string str = "0" uint8_t num = 15 -> string str = "15" uint_t num = 255 -> string str = "255"
怎么做比较好?
1 heijiaotuan123 2022-02-24 17:34:04 +08:00 ![]() |
![]() | 2 bitdepth 2022-02-24 17:36:00 +08:00 ![]() |
![]() | 3 ReputationZh OP @heijiaotuan123 OK ,搞定了。 没怎么用过 c++,脑阔疼,我第一想法是 uint8_t 用 sprintf()转成字符类型,再把 char 数组转成 string ,这样的话又需要考虑结束符位置。啊,头疼。 结贴…… |
![]() | 4 lakehylia 2022-02-24 18:27:18 +08:00 uint8_t 值范围就是 0 - 255 。 uint8_t i = 0; char buf[4]; sprintf(buf, "%d", i); std::string iString(buf); |
![]() | 5 ysc3839 2022-02-24 19:33:21 +08:00 via Android @ReputationZh 如果你要用 sprintf 这种写入缓冲区的函数,可以先用 str.resize() 分配空间,然后用 str.data() 拿到指针。 C++17 之前 str.data() 拿到的指针是带 const 的,按照网上的说法,从 C++11 开始就可以用 &str[0] 来拿到可写的指针。 https://stackoverflow.com/a/39200666 当然,这个问题显然是用 std::to_string() 最好 |
6 lonewolfakela 2022-02-24 23:23:26 +08:00 实话说如果只是 uint8_t 的话甚至可以直接打表…… |
![]() | 7 inframe 2022-02-24 23:30:06 +08:00 sprintf(str,"%d",value) converts to decimal base. sprintf(str,"%x",value) converts to hexadecimal base. sprintf(str,"%o",value) converts to octal base. itoa https://www.cplusplus.com/reference/cstdlib/itoa/ 方法很多很多啊 |
8 qaweqa 2022-02-25 00:41:37 +08:00 std::to_string |
![]() | 9 ReputationZh OP @inframe 目标类型是 string 不是 char* |
![]() | 10 ReputationZh OP @qaweqa 已搞定 |