0

Assume I have a string s that represents a hex value:

string s="0x80";

I want to assign the value of s to v, where v is defined as:

unsigned char v;

What is the simplest way of doing it?


Why do I need it? Because in here, a bloom filter is represented as a vector of unsigned char where each char represents 8 bits. I want to access each char, perform some computation on it, and then store it back in a compatible form. Also, when I print each element of the vector (which is of type unsigned char) it appears in a hex form, e.g. 3a, 98, etc.

3
  • Why are strings involved at all? "vector of unsigned char" is not a string (just use it directly) Commented Sep 3, 2018 at 18:54
  • Assuming the number is always going to fit in an unsigned char, v = std::stoul(s, nullptr, 16); Documentation Commented Sep 3, 2018 at 18:55
  • But it sounds more like you're actually asking how to convert a number to a hex string... or have a fundamental misunderstanding of how numbers are stored in a computer. Commented Sep 3, 2018 at 18:57

2 Answers 2

5
  1. Construct a std::istringstream from the string.
  2. Extract the number from the istringstream by indicating that the stream contains data in hex format.
  3. Assign the number to a char.

std::string s="0x80";
std::istringstream str(s);
int num;
str >> std::hex >> num;

unsigned char v = num;
Sign up to request clarification or add additional context in comments.

1 Comment

note this will ignore any invalid characters, e.g. "0x8G" will parse successfully
4

Convert string to integer:

unsigned char num = std::stoi(s, nullptr, 0);

1 Comment

Shouldn't pass nullptr as the second parameter or the function will silently ignore some errors

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.