How to convert Byte Array to hex string in visual c++?

前端 未结 5 1179
野性不改
野性不改 2021-01-11 16:59

Declaration of a method are following:

//some.h
void TDES_Decryption(BYTE *Data, BYTE *Key, BYTE *InitalVector, int Length);

I am calling t

5条回答
  •  迷失自我
    2021-01-11 17:56

    Here is a somewhat more flexible version (Use uppercase characters? Insert spaces between bytes?) that can be used with plain arrays and various standard containers:

    #include 
    #include 
    #include 
    
    template
    std::string make_hex_string(TInputIter first, TInputIter last, bool use_uppercase = true, bool insert_spaces = false)
    {
        std::ostringstream ss;
        ss << std::hex << std::setfill('0');
        if (use_uppercase)
            ss << std::uppercase;
        while (first != last)
        {
            ss << std::setw(2) << static_cast(*first++);
            if (insert_spaces && first != last)
                ss << " ";
        }
        return ss.str();
    }
    

    Example usage (plain array):

    uint8_t byte_array[] = { 0xDE, 0xAD, 0xC0, 0xDE, 0x00, 0xFF };
    auto from_array = make_hex_string(std::begin(byte_array), std::end(byte_array), true, true);
    assert(from_array == "DE AD C0 DE 00 FF");
    

    Example usage (std::vector):

    // fill with values from the array above
    std::vector byte_vector(std::begin(byte_array), std::end(byte_array));
    auto from_vector = make_hex_string(byte_vector.begin(), byte_vector.end(), false);
    assert(from_vector == "deadc0de00ff");
    

提交回复
热议问题