简体   繁体   中英

Convert Hex to Byte in C++

How do you convert a hex string to short in c++?

Let's say you have

string hexByte = "7F";

How do you convert that to a byte? Which I assume it's a char or int8_t in c++

I tried:

wstring hexString = "7F";
unsigned char byte;
stringstream convert(hexString);
convert >> byte;
// converting from UTF-16 to UTF-8
#include <iostream>       // std::cout, std::hex
#include <string>         // std::string, std::u16string
#include <locale>         // std::wstring_convert
#include <codecvt>        // std::codecvt_utf8_utf16

int main ()
{
  std::u16string str16 (u"\u3084\u3042");  // UTF-16 for YAA (やあ)

  std::wstring_convert<std::codecvt_utf8_utf16<char16_t>,char16_t> cv;

  std::string str8 = cv.to_bytes(str16);

  std::cout << std::hex;

  std::cout << "UTF-8: ";
  for (char c : str8)
    std::cout << '[' << int(static_cast<unsigned char>(c)) << ']';
  std::cout << '\n';

  return 0;
}

http://www.cplusplus.com/reference/locale/wstring_convert/to_bytes/

Convert each character of hex input to integer type

int char2int(char input)
{
  if(input >= '0' && input <= '9')
    return input - '0';
  if(input >= 'A' && input <= 'F')
    return input - 'A' + 10;
  if(input >= 'a' && input <= 'f')
    return input - 'a' + 10;
  throw std::invalid_argument("Invalid input string");
}

// This function assumes src to be a zero terminated sanitized string with
// an even number of [0-9a-f] characters, and target to be sufficiently large
void hex2bin(const char* src, char* target)
{
  while(*src && src[1])
  {
    *(target++) = char2int(*src)*16 + char2int(src[1]);
    src += 2;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM