C++ converting a mac id string into an array of uint8_t

前端 未结 4 1021
小蘑菇
小蘑菇 2021-01-15 17:42

I want to read a mac id from command line and convert it to an array of uint8_t values to use it in a struct. I can not get it to work. I have a vector of stri

4条回答
  •  耶瑟儿~
    2021-01-15 18:19

    Your problem may be in the output of the parsed data. The "<<" operator makes decisions on how to display data based on the data type passed it, and uint8_t may be getting interpretted as a char. Make sure you cast the array values to ints when printing, or investigate in a debugger.

    The sample program:

    uint8_t tgt_mac[6] = {0};
    std::stringstream ss( "AA:BB:CC:DD:EE:11" );
    char trash;
    
    for ( int i = 0; i < 6; i++ )
    {
        int foo;
        ss >> std::hex >> foo >> trash;
        tgt_mac[i] = foo;
        std::cout << std::hex << "Reading: " << foo << std::endl;
    }
    
    std::cout << "As int array: " << std::hex
        << (int) tgt_mac[0]
        << ":"
        << (int) tgt_mac[1]
        << ":"
        << (int) tgt_mac[2]
        << ":"
        << (int) tgt_mac[3]
        << ":"
        << (int) tgt_mac[4]
        << ":"
        << (int) tgt_mac[5]
        << std::endl;
    std::cout << "As unint8_t array: " << std::hex
        << tgt_mac[0]
        << ":"
        << tgt_mac[1]
        << ":"
        << tgt_mac[2]
        << ":"
        << tgt_mac[3]
        << ":"
        << tgt_mac[4]
        << ":"
        << tgt_mac[5]
        << std::endl;
    

    Gives the following output ( cygwin g++ )

    Reading: aa
    Reading: bb
    Reading: cc
    Reading: dd
    Reading: ee
    Reading: 11
    As int array: aa:bb:cc:dd:ee:11
    As unint8_t array: ª:»:I:Y:î:◄
    

提交回复
热议问题