V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
ReputationZh
V2EX  ›  C++

C++ uint8_t 数组转 String 的问题

  •  
  •   ReputationZh · 2022-02-24 17:31:08 +08:00 · 2032 次点击
    这是一个创建于 789 天前的主题,其中的信息可能已经有所发展或是发生改变。

    接收到数据

    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"
    

    怎么做比较好?

    10 条回复    2022-02-25 11:00:15 +08:00
    bitdepth
        2
    bitdepth  
       2022-02-24 17:36:00 +08:00   ❤️ 1
    https://en.cppreference.com/w/cpp/io/c/fprintf
    stringstream::str()
    or
    std::format
    ReputationZh
        3
    ReputationZh  
    OP
       2022-02-24 17:39:31 +08:00
    @heijiaotuan123 OK ,搞定了。

    没怎么用过 c++,脑阔疼,我第一想法是 uint8_t 用 sprintf()转成字符类型,再把 char 数组转成 string ,这样的话又需要考虑结束符位置。啊,头疼。
    结贴……
    lakehylia
        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);
    ysc3839
        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() 最好
    lonewolfakela
        6
    lonewolfakela  
       2022-02-24 23:23:26 +08:00
    实话说如果只是 uint8_t 的话甚至可以直接打表……
    inframe
        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/

    方法很多很多啊
    qaweqa
        8
    qaweqa  
       2022-02-25 00:41:37 +08:00
    std::to_string
    ReputationZh
        9
    ReputationZh  
    OP
       2022-02-25 11:00:03 +08:00
    @inframe 目标类型是 string 不是 char*
    ReputationZh
        10
    ReputationZh  
    OP
       2022-02-25 11:00:15 +08:00
    @qaweqa 已搞定
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5284 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 07:43 · PVG 15:43 · LAX 00:43 · JFK 03:43
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.