V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
ReputationZh
V2EX  ›  C++

C++ uint8_t 数组转 String 的问题

  •  
  •   ReputationZh · Feb 24, 2022 · 3182 views
    This topic created in 1535 days ago, the information mentioned may be changed or developed.

    接收到数据

    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 replies    2022-02-25 11:00:15 +08:00
    bitdepth
        2
    bitdepth  
       Feb 24, 2022   ❤️ 1
    https://en.cppreference.com/w/cpp/io/c/fprintf
    stringstream::str()
    or
    std::format
    ReputationZh
        3
    ReputationZh  
    OP
       Feb 24, 2022
    @heijiaotuan123 OK ,搞定了。

    没怎么用过 c++,脑阔疼,我第一想法是 uint8_t 用 sprintf()转成字符类型,再把 char 数组转成 string ,这样的话又需要考虑结束符位置。啊,头疼。
    结贴……
    lakehylia
        4
    lakehylia  
       Feb 24, 2022
    uint8_t 值范围就是 0 - 255 。
    uint8_t i = 0;
    char buf[4];
    sprintf(buf, "%d", i);
    std::string iString(buf);
    ysc3839
        5
    ysc3839  
       Feb 24, 2022 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  
       Feb 24, 2022
    实话说如果只是 uint8_t 的话甚至可以直接打表……
    inframe
        7
    inframe  
       Feb 24, 2022
    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  
       Feb 25, 2022
    std::to_string
    ReputationZh
        9
    ReputationZh  
    OP
       Feb 25, 2022
    @inframe 目标类型是 string 不是 char*
    ReputationZh
        10
    ReputationZh  
    OP
       Feb 25, 2022
    @qaweqa 已搞定
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3088 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 52ms · UTC 03:37 · PVG 11:37 · LAX 20:37 · JFK 23:37
    ♥ Do have faith in what you're doing.