1

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; 
8
  • Don't spam language tags! Commented Oct 24, 2016 at 1:57
  • @Olaf sorry thought both languages were related in terms of syntax Commented Oct 24, 2016 at 1:58
  • int8_t only exists if you have 8 bits per byte. Show your code. Did you even made some effort on your own? Note: using unsigned types will make your life much easier. Commented Oct 24, 2016 at 1:59
  • @MikeD Read from a std::istringstream using the std::hex I/O manipulator. Commented Oct 24, 2016 at 2:01
  • And you did not add Java, C#, D and Rust just because you could not add more tags then? C and C++ are different languages, please keep that in mind. If someone tells you different: ask where the C++ standard allows VLAs or C has the class keyword. Commented Oct 24, 2016 at 2:01

2 Answers 2

2
// 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/

Sign up to request clarification or add additional context in comments.

Comments

0

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; } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.