Passing hexdump values as string

Viewed 123

I have function which accepts list of hexdump values and they are passed to the function as initializer list parameter and copied to the buffer:

void func(void * buff, std::initializer_list<unsigned char> s) {
  memcpy(buff, s.begin(), s.size());
}

What I want to do that is to pass those values as string like "0x04 0x02 0x01" as well. Both can be passed as string or initializer_list to argument of function above. I know I have to create template to achieve this. That is what I have tried so far. I could not be able to implement as template

void func(void * buff, std::string s) {
    unsigned char arr[s.length() + 1];
    strcpy(arr, s.c_str());
    std::initializer_list<unsigned char> hex_values(arr); 
    memcpy(d, hex_values.begin(), hex_values.size());
  }
1 Answers

You could put the string in a std::istringstream and do formatted input from that:

#include <algorithm>
#include <iterator>

void func(void* buff, const std::string& s) {
    std::istringstream is(s);
    is.setf(is.hex, is.basefield);    // set the istream in hex mode

    // copy hex values from the istream and store in buff
    std::copy(std::istream_iterator<unsigned>(is), 
              std::istream_iterator<unsigned>{},
              static_cast<unsigned char*>(buff)
    );
}

Full example:

#include <algorithm>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <sstream>

void func(void* buff, std::initializer_list<unsigned char> s) {
    std::memcpy(buff, s.begin(), s.size());
}

void func(void* buff, const std::string& s) {
    std::istringstream is(s);
    is.setf(is.hex, is.basefield);    // set the istream in hex mode

    // copy hex values from the istream and store in buff
    std::copy(std::istream_iterator<unsigned>(is), 
              std::istream_iterator<unsigned>{},
              static_cast<unsigned char*>(buff)
    );
}

template <size_t N>
void show(unsigned char(&b)[N]) {
    for(unsigned ch : b) {
        std::cout << std::setw(2) << ch << ' ';
    }
    std::cout << '\n';
}

int main() {
    unsigned char buff[4];
    std::cout << std::hex;

    func(buff, "0x01 0xFF 0x7F 0x80");
    show(buff);
    func(buff, {0x12, 0xF4, 0x1A, 0x17});
    show(buff);
}

Output

 1 ff 7f 80 
12 f4 1a 17 

You could also add a more generic version taking iterators as input:

template<typename It>
void func(void* buff, It begin, It end) {
    std::copy(begin, end, static_cast<unsigned char*>(buff));
}

With SFINAE checking that whatever the iterator is iterating over is convertible to unsigned char, it could look like this:

#include <type_traits>

template<typename It,
    std::enable_if_t<
        std::is_convertible_v<typename std::iterator_traits<It>::value_type,
                              unsigned char>>* = nullptr>
void func(void* buff, It begin, It end) {
    std::copy(begin, end, static_cast<unsigned char*>(buff));
}
Related