C++ uint8_t 数组转 String 的问题

2022-02-24 17:31:08 +08:00
 ReputationZh

接收到数据

uint8_t num;

需要转成 string 类型的数据,不是直接转类型。

uint8_t num = 0   -> string str = "0"
uint8_t num = 15  -> string str = "15"
uint8_t num = 255 -> string str = "255"

怎么做比较好?

2043 次点击
所在节点    C++
10 条回复
heijiaotuan123
2022-02-24 17:34:04 +08:00
bitdepth
2022-02-24 17:36:00 +08:00
https://en.cppreference.com/w/cpp/io/c/fprintf
stringstream::str()
or
std::format
ReputationZh
2022-02-24 17:39:31 +08:00
@heijiaotuan123 OK ,搞定了。

没怎么用过 c++,脑阔疼,我第一想法是 uint8_t 用 sprintf()转成字符类型,再把 char 数组转成 string ,这样的话又需要考虑结束符位置。啊,头疼。
结贴……
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);
ysc3839
2022-02-24 19:33:21 +08:00
@ReputationZh 如果你要用 sprintf 这种写入缓冲区的函数,可以先用 str.resize() 分配空间,然后用 str.data() 拿到指针。
C++17 之前 str.data() 拿到的指针是带 const 的,按照网上的说法,从 C++11 开始就可以用 &str[0] 来拿到可写的指针。
https://stackoverflow.com/a/39200666

当然,这个问题显然是用 std::to_string() 最好
lonewolfakela
2022-02-24 23:23:26 +08:00
实话说如果只是 uint8_t 的话甚至可以直接打表……
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/

方法很多很多啊
qaweqa
2022-02-25 00:41:37 +08:00
std::to_string
ReputationZh
2022-02-25 11:00:03 +08:00
@inframe 目标类型是 string 不是 char*
ReputationZh
2022-02-25 11:00:15 +08:00
@qaweqa 已搞定

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/836214

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX