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

C++ uint8_t 数组转 String 的问题

  •  
  •   ReputationZh · 2022 年 2 月 24 日 · 2967 次点击
    这是一个创建于 1418 天前的主题,其中的信息可能已经有所发展或是发生改变。

    接收到数据

    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 年 2 月 24 日   ❤️ 1
    https://en.cppreference.com/w/cpp/io/c/fprintf
    stringstream::str()
    or
    std::format
    ReputationZh
        3
    ReputationZh  
    OP
       2022 年 2 月 24 日
    @heijiaotuan123 OK ,搞定了。

    没怎么用过 c++,脑阔疼,我第一想法是 uint8_t 用 sprintf()转成字符类型,再把 char 数组转成 string ,这样的话又需要考虑结束符位置。啊,头疼。
    结贴……
    lakehylia
        4
    lakehylia  
       2022 年 2 月 24 日
    uint8_t 值范围就是 0 - 255 。
    uint8_t i = 0;
    char buf[4];
    sprintf(buf, "%d", i);
    std::string iString(buf);
    ysc3839
        5
    ysc3839  
       2022 年 2 月 24 日 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 年 2 月 24 日
    实话说如果只是 uint8_t 的话甚至可以直接打表……
    inframe
        7
    inframe  
       2022 年 2 月 24 日
    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 年 2 月 25 日
    std::to_string
    ReputationZh
        9
    ReputationZh  
    OP
       2022 年 2 月 25 日
    @inframe 目标类型是 string 不是 char*
    ReputationZh
        10
    ReputationZh  
    OP
       2022 年 2 月 25 日
    @qaweqa 已搞定
    关于   ·   帮助文档   ·   自助推广系统   ·   博客   ·   API   ·   FAQ   ·   Solana   ·   3076 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 70ms · UTC 12:59 · PVG 20:59 · LAX 04:59 · JFK 07:59
    ♥ Do have faith in what you're doing.